Mutex用于C ++中的两个线程

时间:2021-05-28 21:01:44

I've created two threads that use a variable declared in main via pthread_create's last argument. I want thread2 to use modify the value of that variable after thread1 is done with a set of particular instructions. I know how we can use mutex in one thread but how about two or more threads? Refer to the following code:

我创建了两个线程,它们使用通过pthread_create的最后一个参数在main中声明的变量。我希望thread2在完成一系列特定指令后使用修改该变量的值。我知道如何在一个线程中使用互斥,但两个或多个线程怎么样?请参阅以下代码:

#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;
}

3 个解决方案

#1


0  

You should lock mutex before accessing the variable and unlock after you finish you finish you job with the variable. Use lock_guard to keep mutex locked and use brackets for lock_guard lifetime. http://www.cplusplus.com/reference/mutex/lock_guard/

您应该在访问变量之前锁定互斥锁,并在完成后使用变量完成解锁。使用lock_guard保持互斥锁,并使用括号执行lock_guard生存期。 http://www.cplusplus.com/reference/mutex/lock_guard/

std::mutex mtx; //global mutex int v; //global variable;

std :: mutex mtx; // global mutex int 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
}

#2


0  

Your use case needs a condition variable combined with a mutex.

您的用例需要一个与互斥锁结合的条件变量。

http://en.cppreference.com/w/cpp/thread/condition_variable

#3


0  

You should create mutex in same place as shared variable. In your case it is main function. Then you need to share this mutex in all threads which are accessing shared variable.

您应该在共享变量的同一位置创建互斥锁。在你的情况下,它是主要功能。然后,您需要在访问共享变量的所有线程*享此互斥锁。

You can share this mutex over global variable or better in same attribute as shared variable. But you will have to define structure where you place variable and mutex together.

您可以在全局变量上共享此互斥锁,或者在与共享变量相同的属性*享此互斥锁。但是您必须定义将变量和互斥体放在一起的结构。

Update

You should lock mutex pthread_mutex_lock(&mutex); before pthread_cond_wait(&cond, &mutex);

你应该锁定互斥锁pthread_mutex_lock(&mutex);在pthread_cond_wait(&cond,&mutex)之前;

The pthread_cond_signal() and pthread_cond_broadcast() functions have no effect if there are no threads currently blocked on cond.

如果cond上当前没有阻塞线程,则pthread_cond_signal()和pthread_cond_broadcast()函数无效。

#1


0  

You should lock mutex before accessing the variable and unlock after you finish you finish you job with the variable. Use lock_guard to keep mutex locked and use brackets for lock_guard lifetime. http://www.cplusplus.com/reference/mutex/lock_guard/

您应该在访问变量之前锁定互斥锁,并在完成后使用变量完成解锁。使用lock_guard保持互斥锁,并使用括号执行lock_guard生存期。 http://www.cplusplus.com/reference/mutex/lock_guard/

std::mutex mtx; //global mutex int v; //global variable;

std :: mutex mtx; // global mutex int 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
}

#2


0  

Your use case needs a condition variable combined with a mutex.

您的用例需要一个与互斥锁结合的条件变量。

http://en.cppreference.com/w/cpp/thread/condition_variable

#3


0  

You should create mutex in same place as shared variable. In your case it is main function. Then you need to share this mutex in all threads which are accessing shared variable.

您应该在共享变量的同一位置创建互斥锁。在你的情况下,它是主要功能。然后,您需要在访问共享变量的所有线程*享此互斥锁。

You can share this mutex over global variable or better in same attribute as shared variable. But you will have to define structure where you place variable and mutex together.

您可以在全局变量上共享此互斥锁,或者在与共享变量相同的属性*享此互斥锁。但是您必须定义将变量和互斥体放在一起的结构。

Update

You should lock mutex pthread_mutex_lock(&mutex); before pthread_cond_wait(&cond, &mutex);

你应该锁定互斥锁pthread_mutex_lock(&mutex);在pthread_cond_wait(&cond,&mutex)之前;

The pthread_cond_signal() and pthread_cond_broadcast() functions have no effect if there are no threads currently blocked on cond.

如果cond上当前没有阻塞线程,则pthread_cond_signal()和pthread_cond_broadcast()函数无效。