2017-06-20 80 views
-1

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

#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 

*

所以在这里我们可以看到,第二个线程来临界区被释放互斥之前。 字符串“在线程中创建2设备之后”对此进行了说明。 如果说在释放互斥体之前的临界区域,这意味着互斥体的工作是错误的。

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

感谢

+0

不要手动锁定和解锁互斥锁。这样做会使您有可能漏锁。改为使用'std :: lock_guard'或'std :: unique_lock'。 –

回答

4

编辑:tkausl的答案是正确的 - 但是,即使你切换到使用全球互斥,输出可能不是因为在我的答案细节的,所以我离开这里改变它。换句话说,输出可能不是你所期望的有两个原因,你需要解决这两个问题。


请特别注意以下两行:

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

你似乎是的印象是,这两条线将运行在一个又一个的权利,但也不能保证这不会发生在抢先的多线程环境中。可能发生的情况是mtx.unlock()之后可能会有一个上下文切换到另一个线程。

换句话说,第二螺纹等待互斥体解锁,但第二个线程抢占它之前第一线程不打印的“解除分配”的消息。

获得预期输出的最简单方法是交换这两行的顺序。

6

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

1

在调用pthread_create之前,您应将您的互斥量声明为全局变量并启动它。您使用pthread_create创建了两个线程,并且它们都创建了自己的互斥锁,因此它们之间完全没有同步。