为什么这个小的c ++ 11多线程程序给出了分段错误

时间:2014-01-08 12:38:36

标签: multithreading c++11 race-condition undefined-behavior

为什么这个程序给出了seg错误。我尝试使用gdb解决问题,但没有运气。

#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>

using namespace std;

condition_variable cv;
mutex cv_m;

mutex m;

int  count = 0;
#define COUNT_DONE  10
#define COUNT_HALT1  3
#define COUNT_HALT2  6

void functionCount1()
{
   for(;;)
   {
        m.lock();
        count++;
        cout << "Counter value functioncount1: " << count << endl;
        m.unlock();

        if(count >= COUNT_DONE)
                return;
    }
}

void functionCount2()
{
    for(;;)
    {
        m.lock();
        count++;
        cout << "Counter value functionCount2: " << count << endl;
        m.unlock();

        if(count >= COUNT_DONE) return;
    }
}

int main()
{
    thread t1(functionCount1), t2(functionCount2);
    t1.join();
    t2.join();
    return 0;
}

1 个答案:

答案 0 :(得分:2)

您的程序有未定义的行为:countfunctionCount1中互斥体外functionCount2的访问是数据争用。 With the UB corrected, it seems fine

#include <iostream>
#include <mutex>
#include <thread>

using namespace std;

mutex m;
int  count = 0;
#define COUNT_DONE  10

void functionCount(const char* name)
{
   for(;;)
   {
        m.lock();
        auto c = ++count;
        m.unlock();

        cout << "Counter value " << name << ": " << c << endl;
        if(c >= COUNT_DONE)
                return;
    }
}

int main()
{
    thread t1(functionCount, "functionCount1"), t2(functionCount, "functionCount2");
    t1.join();
    t2.join();
}

或者如果你想“聪明”并且混淆你的代码审查者:

void functionCount(const char* name)
{
    for(;;)
    {
        auto c = (std::lock_guard<std::mutex>(m), count++);
        cout << "Counter value " << name << ": " << c << endl;
        if(c >= count_done)
            break;
    }
}