我创建了两个线程,它们使用通过 pthread_create 的最后一个参数在 main 中声明的变量。我希望 thread2 在 thread1 完成一组特定指令后使用修改该变量的值。我知道我们如何在一个线程中使用互斥锁,但是两个或更多线程呢? 引用以下代码:
#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#define NUM 6
using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *even(void *arg)
{
int sum = 0;
int count = 0;
for (int i = 1; count < NUM/2; i++)
{
if( !(i % 2) )
{
count++;
sum += i;
}
}
cout << "In Even Thread: " << sum << endl;
pthread_mutex_lock(&mutex);
*((int*)arg) = sum;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
void *odd(void *arg)
{
int sum = 0;
int count = 0;
for (int i = 1; count < NUM/2; i++)
{
if( i % 2 )
{
count++;
sum += i;
}
}
cout << "In Odd Thread: " << sum << endl;
pthread_cond_wait(&cond, &mutex);
*((int*)arg) = *((int*)arg) + sum;
}
int main()
{
int mainSum = 0;
pthread_t tidO, tidE;
pthread_create(&tidO, NULL, odd, (void *)&mainSum);
pthread_create(&tidE, NULL, even, (void *)&mainSum);
pthread_join(tidO, NULL);
pthread_join(tidE, NULL);
cout << "Sum of first " << NUM << " Natural Numbers: " << mainSum << endl;
return 0;
}
最佳答案
您应该在访问变量之前锁定互斥锁,并在完成对变量的工作后解锁。使用 lock_guard 保持互斥锁锁定,并使用括号来锁定 lock_guard 生命周期。 http://www.cplusplus.com/reference/mutex/lock_guard/
std::互斥锁;//全局互斥锁 诠释五;//全局变量;
int k;
...
//repeat this code in each thread to access the variable
{
std::lock_guard<std::mutex> lck (mtx);
//access the variable;
k = v; //read global variable or
v = k; //write
}
关于c++ - C++中两个线程的互斥量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47303294/