Mutex无法按预期工作

Ale*_* D. 0 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;
}
Run Code Online (Sandbox Code Playgroud)

结果是:

*预期有四到五个参数.

   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
Run Code Online (Sandbox Code Playgroud)

*

所以在这里我们可以看到,在释放互斥锁之前,第二个线程进入临界区.字符串"在线程中创建2个设备后"说明了这一点.如果在解除分配mutex之前涉及临界区,则意味着互斥锁工作错误.

如果您有任何想法请分享.

谢谢

tka*_*usl 6

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