做的网站每年都要收费吗,有没有做网页的兼职网站,西安网吧,apache添加网站主线程创建4个子线程T1、T2、T3、T4#xff0c;主线程在4个子线程退出后#xff0c;才退出线程T1、T2、T3、T4的运行时代码如下#xff1a;
#include unistd.h // sleep函数声明在该头文件中void *T1_entry(void *arg)
{sleep(2); // 睡眠2秒#xff0c;不准删除…主线程创建4个子线程T1、T2、T3、T4主线程在4个子线程退出后才退出线程T1、T2、T3、T4的运行时代码如下
#include unistd.h // sleep函数声明在该头文件中void *T1_entry(void *arg)
{sleep(2); // 睡眠2秒不准删除此条语句否则答题无效puts(“T1”);
}void *T2_entry(void *arg)
{sleep(1); // 睡眠1秒不准删除此条语句否则答题无效puts(“T2”);
}void *T3_entry(void *arg)
{sleep(1); // 睡眠1秒不准删除此条语句否则答题无效puts(“T3”);
}void *T4_entry(void *arg)
{puts(“T4”);
}
使用信号量或者条件变量机制(而不是使用sleep函数)使得这四个线程满足如下制约关系 T1的print语句执行后T2和T3才可以执行print语句T2和T3的print语句执行后T4才可以执行print语句程序输出结果为
T1
T2
T3
T4
或者
T1
T3
T2
T4
code:
#includestdlib.h
#includestdio.h
#includestring.h
#includeunistd.h
#includepthread.hint count0;pthread_mutex_t mutex;
pthread_cond_t wait1;
pthread_cond_t wait2;
pthread_cond_t wait3;void *T1_entry(void *arg){int *parg;pthread_mutex_lock(mutex);while(count!(*p))pthread_cond_wait(wait1,mutex);sleep(2);puts(T1);count;pthread_cond_broadcast(wait2);pthread_mutex_unlock(mutex);
}void *T2_entry(void *arg){int *parg;pthread_mutex_lock(mutex);while(count1||count2)pthread_cond_wait(wait2,mutex);sleep(1);puts(T2);count;pthread_cond_signal(wait3);pthread_mutex_unlock(mutex);
}void *T3_entry(void *arg){int *parg;pthread_mutex_lock(mutex);while(count1||count2)pthread_cond_wait(wait2,mutex);sleep(1);puts(T3);count;pthread_cond_signal(wait3);pthread_mutex_unlock(mutex);
}void *T4_entry(void *arg){int *parg;pthread_mutex_lock(mutex);while(count!(*p))pthread_cond_wait(wait3,mutex);puts(T4);pthread_mutex_unlock(mutex);
}int main(){pthread_t pid[4];int j[4];int i;pthread_mutex_init(mutex,NULL);pthread_cond_init(wait1,NULL);pthread_cond_init(wait2,NULL);pthread_cond_init(wait3,NULL);for(i0;i4;i){j[i]i;if(i0)pthread_create(pid[i],NULL,T1_entry,(void*)j[i]);if(i1)pthread_create(pid[i],NULL,T2_entry,(void*)j[i]);if(i2)pthread_create(pid[i],NULL,T3_entry,(void*)j[i]);if(i3)pthread_create(pid[i],NULL,T4_entry,(void*)j[i]);}pthread_join(pid[3],NULL);return 0;
}