一段使用 mutex 和 条件变量 pthread_cond_wait 的例子
#include <iostream>
#include <pthread.h>
#include <string>
#include <unistd.h>
using namespace std;
int Number = 0;
pthread_mutex_t NMutex;
pthread_cond_t NCond;
void *thread1(void *arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&NMutex);
while (Number <= 0 )//等待主线程读入Number
pthread_cond_wait(&NCond, &NMutex);
int Count = Number;
int Sum = 1;
for (int i = 1; i < Count; i++)
Sum += i;
cout << "count by thread1 is " << Sum << endl;
pthread_mutex_unlock(&NMutex);
return NULL;
}
void *thread2(void *arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&NMutex);
while (Number <= 0 )//等待主线程读入Number
pthread_cond_wait(&NCond, &NMutex);
int Count = Number;
int Sum = 1;
for (int i = 1; i < Count; i++)
Sum += i;
cout << "count by thread2 is " << Sum << endl;
pthread_mutex_unlock(&NMutex);
return NULL;
}
int main(int argc, char* argv[])
{
pthread_mutex_init(&NMutex, NULL);
pthread_cond_init(&NCond, NULL);
pthread_t p1, p2;
pthread_create(&p1, NULL, thread1, NULL);
pthread_create(&p2, NULL, thread2, NULL);
#include <pthread.h>
#include <string>
#include <unistd.h>
using namespace std;
int Number = 0;
pthread_mutex_t NMutex;
pthread_cond_t NCond;
void *thread1(void *arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&NMutex);
while (Number <= 0 )//等待主线程读入Number
pthread_cond_wait(&NCond, &NMutex);
int Count = Number;
int Sum = 1;
for (int i = 1; i < Count; i++)
Sum += i;
cout << "count by thread1 is " << Sum << endl;
pthread_mutex_unlock(&NMutex);
return NULL;
}
void *thread2(void *arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&NMutex);
while (Number <= 0 )//等待主线程读入Number
pthread_cond_wait(&NCond, &NMutex);
int Count = Number;
int Sum = 1;
for (int i = 1; i < Count; i++)
Sum += i;
cout << "count by thread2 is " << Sum << endl;
pthread_mutex_unlock(&NMutex);
return NULL;
}
int main(int argc, char* argv[])
{
pthread_mutex_init(&NMutex, NULL);
pthread_cond_init(&NCond, NULL);
pthread_t p1, p2;
pthread_create(&p1, NULL, thread1, NULL);
pthread_create(&p2, NULL, thread2, NULL);
//begin input
pthread_mutex_lock(&NMutex);
cout << "input a number ";
cin >> Number;
pthread_mutex_unlock(&NMutex);
pthread_cond_signal(&NCond);
//end input
cin >> Number;
pthread_mutex_unlock(&NMutex);
pthread_cond_signal(&NCond);
//end input
pthread_exit(NULL);
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步