#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t lockid;
pthread_cond_t cvar = PTHREAD_COND_INITIALIZER;
char name[14];
void *entry()
{
pthread_mutex_lock(&lockid);
printf("Enter Name\n");
scanf("%s",name);
pthread_cond_signal(&cvar);
pthread_mutex_unlock(&lockid);
pthread_exit(NULL);
}
void *display()
{
pthread_mutex_lock(&lockid);
pthread_cond_wait(&cvar,&lockid);
printf("Name: %s\n",name);
pthread_mutex_unlock(&lockid);
pthread_exit(NULL);
}
int main()
{
pthread_t id1,id2;
if(pthread_mutex_init(&lockid,NULL)== 0){
pthread_create(&id1,NULL,&entry,NULL);
pthread_create(&id2,NULL,&display,NULL);
pthread_join(id1,NULL);
pthread_join(id2,NULL);
}
return 0;
}
我期望執行緒 id2 列印我在執行緒 id1 上輸入的名稱。我知道這是pthread_cond_wait()不允許執行緒id2顯示在執行緒上輸入的名稱,id1但signal()應該在之前呼叫wait()對嗎?呼叫方式wait()和signal()方法是否正確?我是 linux 編程的新手,請幫助我。
uj5u.com熱心網友回復:
如果您有一個順序任務,請不要使用執行緒:
#include <stdio.h>
char name[14];
int main() {
printf("Enter Name\n");
scanf("%s",name);
printf("Name: %s\n", name);
return 0
}
您可以使用state變數來確保在entry()運行之前display():
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
pthread_mutex_t lockid;
pthread_cond_t cvar = PTHREAD_COND_INITIALIZER;
char name[14];
enum { START, ENTRY } state = START;
#define CHECK(e) { int error = (e); if(error) printf("%s:%d %s", __FILE__, __LINE__, strerror(error)); }
#define CHECK2(p, e) { if(p) CHECK(e); }
void *entry() {
CHECK(pthread_mutex_lock(&lockid));
printf("Enter Name\n");
CHECK2(scanf("%s", name) == EOF, errno);
state = ENTRY;
pthread_cond_signal(&cvar);
CHECK(pthread_mutex_unlock(&lockid));
return 0;
}
void *display() {
CHECK(pthread_mutex_lock(&lockid));
while(state != ENTRY) pthread_cond_wait(&cvar, &lockid);
printf("Name: %s\n", name);
CHECK(pthread_mutex_unlock(&lockid));
return 0;
}
int main() {
pthread_mutex_init(&lockid, NULL);
pthread_t id1, id2;
CHECK(pthread_create(&id1, NULL, &entry, NULL));
CHECK(pthread_create(&id2, NULL, &display, NULL));
CHECK(pthread_join(id1,NULL));
CHECK(pthread_join(id2,NULL));
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/359329.html
上一篇:如果可能有多個服務器(并且每個服務器都可以有多個執行緒),如何處理競爭條件
下一篇:最終List<T>和執行緒安全
