C++中两个线程的互斥体
Mutex for two threads in C++
我创建了两个线程,它们使用通过 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::mutex mtx;//global mutexint v;全局变量;
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
}
您的用例需要将条件变量与互斥锁结合使用。
http://en.cppreference.com/w/cpp/thread/condition_variable
您应该在与共享变量相同的位置创建互斥锁。在您的情况下,它是主要功能。然后,您需要在所有访问共享变量的线程中共享此互斥锁。
您可以通过全局变量共享此互斥锁,或者在与共享变量相同的属性中共享此互斥锁。但是你必须定义将变量和互斥锁放在一起的结构。
更新
您应该在pthread_cond_wait(&cond, &mutex);
之前锁定互斥锁pthread_mutex_lock(&mutex);
如果 cond 上当前没有阻塞线程,则 pthread_cond_signal(( 和 pthread_cond_broadcast(( 函数不起作用。
相关文章:
- 在两个线程上读/写 64 位,无互斥/锁定/原子
- 通过插槽和信号在不同线程中的两个qt对象之间进行通信
- 如果两个线程相互依赖,则 cpp 线程连接应使用连接导致死锁
- 两个线程一个使用流 Api,另一个线程创建文件失败并出现错误ERROR_SHARING_VIOLATION
- 简单使用 std::atomic 在两个线程之间共享数据
- 如何在Qt中合并/追加/添加两个用于线程的模型?
- 如何从两个平行的线程中停止一个线程
- 如何使用 pthreads 以正确的方式设置两个线程之一的优先级
- 曼德布洛特 从一个线程被反复使用变为两个线程
- C++ 两个线程,共享几个整数变量
- 如何正确同步这两个线程?
- Qt多线程:如何更新两个QLabel?
- 两个线程尝试将一些数据读/写到数据库中表的同一行中
- 两个线程的公共资源 - 同步足够吗?
- Qt 线程两个参数
- 我们是否需要每个线程多个io_service用于具有单个接受器的线程 boost::asio 服务器
- 将一条线从两个点延伸到一定长度
- C++11线程:多个线程正在等待一个条件变量
- 多线程两个功能使用openMP
- 单线程两个进程