我是 pthread 编程的新手。我正在编写一个示例代码,我想在其中传输 pthread_cond_signal() 中的变量,如下所示
pthread_t th1,th2;
pthread_cond_t con1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t con2 = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* fun(void *gh)
{
pthread_mutex_lock(&mutex);
flag=1;
pthread_cond_wait(&con1,&mutex);
printf("This is test\n");
pthread_mutex_unlock(&mutex);
}
int main()
{
char *s;
int a;
s=malloc(sizeof(char)*4);
printf("Enter thread Number \n");
scanf("%d",&a);
sprintf(s,"con%d",a);
pthread_create(&th1,NULL,fun,NULL);
sleep(1);
while(flag==0) //wait until pthread_cond_wait is called
{}
pthread_mutex_lock(&mutex);
pthread_cond_signal((pthread_cond_t *)s);
pthread_mutex_unlock(&mutex);
pthread_join(th1,NULL);
pthread_join(th2,NULL);
return 0;
}