c++ - Mutex 没有按预期工作

标签 c++ multithreading mutex

我在继承的类中使用了互斥锁,但它似乎不能像我预期的那样在线程中工作。请看下面的代码:

#include <iostream>
#include <cstdlib>
#include <pthread.h>

// mutex::lock/unlock
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <chrono>         // std::thread
#include <mutex>          // std::mutex

typedef unsigned int UINT32t;
typedef int INT32t;

using namespace std;



class Abstract {

protected:
    std::mutex mtx;
};


class Derived: public Abstract
{
public:
    void* write( void* result)
    {
        UINT32t error[1];
        UINT32t data = 34;
        INT32t length = 0;
        static INT32t counter = 0;

        cout << "\t   before Locking ..." << " in thread"  << endl;

        mtx.lock();
        //critical section
        cout << "\t    After Create " << ++ counter  << " device in thread"  << endl;

        std::this_thread::sleep_for(1s);

        mtx.unlock();
        cout << "\t    deallocated " << counter << " device in thread"  << endl;
        pthread_exit(result);
    }
};

void* threadTest1( void* result)
{
    Derived dev;

    dev.write(nullptr);
}


int main()
{
    unsigned char byData[1024] = {0};
    ssize_t len;
    void *status = 0, *status2 = 0;
    int result = 0, result2 = 0;

    pthread_t pth, pth2;
    pthread_create(&pth, NULL, threadTest1, &result);
    pthread_create(&pth2, NULL, threadTest1, &result2);


    //wait for all kids to complete
    pthread_join(pth, &status);
    pthread_join(pth2, &status2);

    if (status != 0) {
           printf("result : %d\n",result);
       } else {
           printf("thread failed\n");
       }


    if (status2 != 0) {
           printf("result2 : %d\n",result2);
       } else {
           printf("thread2 failed\n");
       }


    return -1;
}

所以结果是:

*预期有四个或五个参数。

   before Locking ... in thread
    After Create 1 device in thread
   before Locking ... in thread
    After Create 2 device in thread
    deallocated 2 device in thread
    deallocated 2 device in thread
       thread failed
       thread2 failed

*

所以在这里我们可以看到第二个线程在互斥体被释放之前进入临界区。 字符串“After Create 2 device in thread”说明了这一点。 如果在释放互斥锁之前到达临界区,则意味着互斥锁工作错误。

如果您有任何想法,请分享。

谢谢

最佳答案

互斥量本身(可能)工作正常(虽然我建议您使用 std::lock_guard),但是两个线程都创建了它们自己的 Derived 对象,因此,它们不使用相同的互斥体。

关于c++ - Mutex 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44657827/

相关文章:

c - Linux 上的 RPC 多线程服务器 - Pthreads

python - Python 和 PyQt 中的线程错误

multithreading - 轻量级互斥

c++ - 线程常量错误 C++

c++ - 为多个平台构建 Linux 二进制文件

c++ - std::string 在参数中构造

c++ - 使用显式非类型参数和隐式类型参数调用模板函数

c++ - 用于解析资源 (.rc) 文件的正则表达式

multithreading - 卡在Rust中的 channel 接收器迭代器上?

c++ - 共享内存中的 std::mutex 不工作