C++中两个线程的互斥体

Mutex for two threads in C++

本文关键字:线程 两个 C++      更新时间:2023-10-16

我创建了两个线程,它们使用通过 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(( 函数不起作用。