c++ - C++中两个线程的互斥量

标签 c++ linux pthreads mutex

我创建了两个线程,它们使用通过 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/

相关文章:

c++ - 获取当前按键的简单方法

c++错误没有匹配函数

php - 如何在 Amazon AMI EC2 微型实例上安装 GearmanManager?

php - 在主机上上传项目后禁止访问

c - 为什么此 pthreads 代码在 OS X 上始终出现段错误,但在 Linux 上却没有?

c++ - 如果您打算让变量在超出范围后保留,您在哪里调用delete?

c++ - 如何区分 Clang AST 访问者中的函数定义和函数声明

c++ - Borland C++ - 使用 OLE 使用 Word 打开 RTF 文件

c++ - 在 ubuntu 上编译 lsnes 模拟器时出错

c - FastCGI 在 c 中的分支