【问题标题】:pthread_cond_wait/signal and mutex not working as expectedpthread_cond_wait/signal 和 mutex 未按预期工作
【发布时间】:2016-02-22 23:27:50
【问题描述】:

我正在尝试学习 pthread/mutex,但尽管在网上进行了大量研究/阅读,但我无法理解这段代码出了什么问题:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

struct data
{
    int Counter = 0;
    int calls = -1;
    int iteration = -1;
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
};

void* threadAlarm (void* arg);
void* threadCounter (void* arg);

int main (void)
{
    pthread_t monThreadCounter;
    pthread_t monThreadAlarm;

    struct data mydata;

    if (pthread_create (&monThreadAlarm, NULL, threadAlarm,(void*)&mydata)>0)
        printf("Pthread Alarme error\n");
    if (pthread_create (&monThreadCounter, NULL, threadCounter, (void*)&mydata)>0)
        printf("Pthread Counter error\n");

    pthread_join (monThreadCounter, NULL);
    pthread_join (monThreadAlarm, NULL);

    return 0;
}

void* threadCounter (void *arg)
{
    struct data *myarg = (struct data *)arg;
    srand(time(NULL));

    pthread_mutex_lock (&myarg->mutex);

    while(1)
    {
        myarg->Counter += rand()%10; /* We add a random number to the counter */

        if(myarg->Counter > 20) /* If Counter is greater than 20, we should trigger the alarm*/
        {
            myarg->iteration += 1; /* Iteration counter, to check any shift between expected triggers and reality */

            printf("Counter = %i(%i)-->",myarg->Counter,myarg->iteration);

            pthread_mutex_unlock (&myarg->mutex); /* Unlock mutex before sending signal */

            if (pthread_cond_signal (&myarg->condition) >0)
            {
                printf("COND SIGNAL ERROR\n");
                pthread_exit(NULL);
            }

            usleep(10000); /* The shorter the sleep is, the weirder the output is */

            pthread_mutex_lock (&myarg->mutex); /* We should get the lock again before testing/modifying any shared variable */
        }
    }
}

void* threadAlarm (void* arg)
{
    struct data *myarg = (struct data *)arg;

    while(1)
    {
        pthread_mutex_lock(&myarg->mutex);

        //while(myarg->Counter<21) // Uneeded? Since we'll never get the lock before the Counter thread detects condition and release it
        {
            printf("\nWAITING for trigger...\n",myarg->Counter);
            if (pthread_cond_wait (&myarg->condition, &myarg->mutex)>0)
            {
                printf("ERROR COND WAIT\n");
                pthread_exit(NULL);
            }
        }

        myarg->calls+=1; // Calls counter, should be equal to iteration counter, overwise calls have been missed

        printf("ALARM TRIGGERED! Call #%i/Iteration #%i -> COUNTER RESET\n",myarg->calls, myarg->iteration);

        // Counter reset
        myarg->Counter = 0;

        pthread_mutex_unlock(&myarg->mutex);
    }
}

此代码应该有一个线程将计数器增加一个随机值,直到它大于 20,然后会触发另一个等待线程的条件,该线程应该显示一条消息并重置计数器。以此类推。

我不明白的是,尽管我认为我正在使用互斥锁、pthread_cond_wait 和 pthread_cond_signal,如网络上的各种示例中所述,但如果我不引入睡眠来减慢它的速度,它的行为就不会像预期的那样下来。

使用usleep(10000),我得到了预期的输出:

WAITING for trigger...
Counter = 23(59)-->ALARM TRIGGERED! Call #59/Iteration #59 -> COUNTER RESET

WAITING for trigger...
Counter = 23(60)-->ALARM TRIGGERED! Call #60/Iteration #60 -> COUNTER RESET

WAITING for trigger...
Counter = 21(61)-->ALARM TRIGGERED! Call #61/Iteration #61 -> COUNTER RESET

调用/迭代计数器是同步的,证明每次达到条件时,都会正确触发“警报”线程。

但是,如果我减少睡眠,结果会变得很奇怪。根本没有睡觉(注释掉),例如:

WAITING for trigger...
Counter = 21(57916)-->Counter = 23(57917)-->Counter = 29(57918)-->Counter = 38(57919)-->Counter = 45(57920)-->Counter = 45(57921)-->Counter = 45(57922)-->Counter = 49(57923)-->Counter = 52(57924)-->Counter = 55(57925)-->Counter = 61(57926)-->Counter = 65(57927)-->Counter = 70(57928)-->Counter = 77(57929)-->Counter = 83(57930)-->Counter = 86(57931)-->Counter = 92(57932)-->Counter = 95(57933)-->Counter = 99(57934)-->Counter = 107(57935)-->ALARM TRIGGERED! Call #4665/Iteration #57935 -> COUNTER RESET

WAITING for trigger...
Counter = 24(57936)-->Counter = 28(57937)-->Counter = 31(57938)-->Counter = 31(57939)-->Counter = 36(57940)-->Counter = 41(57941)-->Counter = 45(57942)-->Counter = 47(57943)-->Counter = 54(57944)-->Counter = 54(57945)-->Counter = 56(57946)-->Counter = 62(57947)-->Counter = 64(57948)-->Counter = 66(57949)-->Counter = 66

...

尽管计数器已经达到触发状态,但似乎并没有触发警报线程并继续增加,并且调用/迭代计数器完全不同步,证明错过了许多调用。

如何确保每次发出 pthread_cond_signal 时,等待线程都被真正触发,而调用线程将一直等待,直到被触发线程释放互斥锁?

以防万一,我目前正在 Linux Ubuntu 上进行编码。

感谢您的帮助。

【问题讨论】:

  • 您不能将初始化程序放入结构的定义中。你是怎么编译的?
  • pthread_mutex_lock()pthread_mutex_unlock() 和 pthread_cond_signal() 的返回值是多少?
  • 看起来代码更像是 C++ 而不是 C,是这样吗?确保将这两种语言分开!在 C++ 中,您通常也不会使用 POSIX 线程,而是使用它们自己的线程。也就是说,在等待条件变量后醒来时,您必须检查实际条件!阿尔斯,你甚至需要在睡觉之前这样做!这些都是常见的错误,可能来自“条件变量”这个名字,有点误导。
  • >Andrew Henle:互斥锁和解锁总是返回 0(无错误)
  • >Ulrich Eckhardt:你说得对,这是一个 C++ 项目。您能否详细说明为什么我应该将这两种语言分开?

标签: c++ linux multithreading pthreads mutex


【解决方案1】:

这是预期的行为。一旦您向条件变量发出信号,等待的线程最终会唤醒并争夺互斥锁,但不能保证在此之前发出信号的线程将无法重新获取互斥锁。

如果您希望计数器线程等待警报被消耗,您需要对其进行实际编程来执行此操作。您可以反过来使用相同的条件变量 - 在计数器线程中:

if (pthread_cond_signal (&myarg->condition) >0)
{
    printf("COND SIGNAL ERROR\n");
    pthread_exit(NULL);
}

pthread_mutex_lock (&myarg->mutex); /* We should get the lock again before testing/modifying any shared variable */

/* Wait for alarm to happen */
while (myarg->calls < myarg->iteration)
{
    pthread_cond_wait(&myarg->condition, &myarg->mutex);
}

在警报线程中,在增加 myarg-&gt;calls 后的某个时间点调用 pthread_cond_signal(&amp;myarg-&gt;condition)


顺便说一句,您确实需要您在警报线程中注释掉的while(myarg-&gt;Counter&lt;21)。考虑以下两种情况:

  1. 警报线程在其主循环开始时被阻塞在pthread_mutex_lock()。计数器线程拥有互斥锁,并且刚刚将myarg-&gt;Counter 增加到大于 20 的值。它解锁互斥锁并向条件变量发出信号,警报线程有机会运行之前。然后警报线程运行,获取互斥体并在pthread_cond_wait() 中阻塞 - 它将永远在这里等待,因为我们现在已确保计数器线程将在继续之前等待警报被消耗。

    李>
  2. 警报线程刚刚将计数器减为零,解锁互斥体,立即在循环顶部重新锁定它并调用pthread_cond_wait()pthread_cond_wait() 在计数器线程有机会获取互斥锁之前立即返回(由于“虚假唤醒”,这是允许的),即使计数器仍然为零,警报线程现在仍将继续。

【讨论】:

  • 在 2 个线程之间添加“反向”条件/等待可以解决“未接来电”问题,但有时会碰巧保持在警报线程中。取消注释while(myarg-&gt;Counter&lt;21)解决第二个问题,现在一切似乎都运行良好。我不得不说,我在网上阅读的所有示例都没有显示正确使用等待/信号。我的示例受到a lesson from openclassrooms.com(法语)的启发,这显然是错误的!
【解决方案2】:

这是工作版本,以防它对其他人有用:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>


struct data
{
    int Counter = 0;
    int calls = -1;
    int iteration = -1;
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
};

void* threadAlarm (void* arg);
void* threadCounter (void* arg);

int main (void)
{
    pthread_t monThreadCounter;
    pthread_t monThreadAlarm;

    struct data mydata;

    if (pthread_create (&monThreadAlarm, NULL, threadAlarm, (void*)&mydata)>0)
        printf("Pthread Alarme error\n");
    if (pthread_create (&monThreadCounter, NULL, threadCounter, (void*)&mydata)>0)
        printf("Pthread Counter error\n");

    pthread_join (monThreadCounter, NULL);
    pthread_join (monThreadAlarm, NULL);

    return 0;
}

void* threadCounter (void *arg)
{
    struct data *myarg = (struct data *)arg;
    srand(time(NULL));

    if (pthread_mutex_lock(&myarg->mutex) > 0)
        {
            printf("ERROR Mutex lock1 Counter\n");
            pthread_exit(NULL);
        }

    while(1)
    {
        myarg->Counter += rand()%10; /* We add a random number to the counter */

        if(myarg->Counter > 20) /* If Counter is greater than 20, we should trigger the alarm*/
        {
            myarg->iteration += 1; /* Iteration counter, to check any shift between expected triggers and reality */

            printf("Counter = %i(%i)-->",myarg->Counter,myarg->iteration);

            if (pthread_mutex_unlock(&myarg->mutex) > 0) /* Unlock mutex before sending signal */
                {
                    printf("ERROR Mutex Unlock Counter\n");
                    pthread_exit(NULL);
                }

            if (pthread_cond_signal (&myarg->condition) >0)
            {
                printf("COND SIGNAL ERROR\n");
                pthread_exit(NULL);
            }

            if (pthread_mutex_lock(&myarg->mutex) > 0) /* We should get the lock again before testing/modifying any shared variable */
                {
                    printf("ERROR Mutex lock2 Counter\n");
                    pthread_exit(NULL);
                }

            /* Wait for alarm to happen */
            while (myarg->calls < myarg->iteration)
            {
                pthread_cond_wait(&myarg->condition, &myarg->mutex);
            }
        }
    }
}

void* threadAlarm (void* arg)
{
    struct data *myarg = (struct data *)arg;

    while(1)
    {
        if (pthread_mutex_lock(&myarg->mutex) > 0)
            {
                printf("ERROR Mutex lock Alarm\n");
                pthread_exit(NULL);
            }

        while(myarg->Counter<21)
        {
            printf("\nWAITING for trigger...\n");
            if (pthread_cond_wait (&myarg->condition, &myarg->mutex)>0)
            {
                printf("ERROR COND WAIT\n");
                pthread_exit(NULL);
            }
        }

        myarg->calls+=1; // Calls counter, should be equal to iteration counter, overwise calls have been missed

        printf("ALARM TRIGGERED! Call #%i/Iteration #%i -> COUNTER RESET\n",myarg->calls, myarg->iteration);

        // Counter reset
        myarg->Counter = 0;

        if (pthread_mutex_unlock(&myarg->mutex) > 0)
            {
                printf("ERROR Mutex Unlock Alarm\n");
                pthread_exit(NULL);
            }


        if (pthread_cond_signal (&myarg->condition) >0) //Signal back to Counter thread
        {
            printf("COND SIGNAL ERROR\n");
            pthread_exit(NULL);
        }

    }
}

【讨论】:

    猜你喜欢
    • 2016-08-13
    • 2018-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 1970-01-01
    相关资源
    最近更新 更多