0
我是pthread編程的新手。我正在寫一個示例代碼,我想在pthread_cond_signal()中傳遞變量,如下所示:如何在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;
}
此外,你的while(flag == 0)循環可能永遠不會結束。您需要鎖定每次訪問標誌的位置,否則代碼可能永遠不會讀取標誌,因爲它可能會加載到寄存器中,或者可能會在程序中優化。 –