【发布时间】:2015-11-02 01:14:13
【问题描述】:
#include < iostream >
#include < pthread.h >
using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* Func(void *)
{
pthread_mutex_lock(&mutex);
cout << "First thread execution" << endl;
pthread_mutex_unlock(&mutex);
}
int main()
{
pthread_t th1;
pthread_create(&th1, NULL, Func, NULL);
pthread_mutex_lock(&mutex);
cout << "In main thread" << endl;
pthread_mutex_lock(&mutex);
// pthread_join(th1, NULL); // Note this code is commented
return 0;
}
我在 linux fedora 22(也在 http://www.cpp.sh/)上执行了大约 20 次以下程序,在 20 次执行中我发现了以下输出:-
输出1:
In main thread
First thread execution
输出2:
First thread execution
In main thread
输出3:
In main thread
输出4:
In main thread
First thread execution
First thread execution
输出 1 到 3 是预期的,因为主线程没有等待子线程退出。两个线程(主线程和子线程)的执行顺序完全依赖于内核线程调度。
但是输出 4 很奇怪!!! First thread execution 被打印两次!!!
现在,如果我在取消注释代码 'pthread_join(th1, NULL)' 或添加 'pthread_exit(NULL)' 之后运行程序,我不会得到奇怪的输出(即 First thread execution 从未打印过两次),即使我运行编码 10000 次。
我对专家的问题是:
- 如果没有 pthread_join/pthread_exit,幕后会发生什么导致
First thread execution被打印了 2 次?
pthread_join 的职责是获取特定线程的退出代码,在成功调用 pthread_join 后,内核将释放该特定线程的资源。如果我不在可连接线程上调用 pthread_join 则会导致资源泄漏,但是为什么上面提到的奇怪行为呢??
我们可能会说,这是未定义的行为,但如果有专家对此提供技术解释,那就太好了。
- pthread_join/pthread_exit 如何防止上述奇怪行为?由于没有出现这种奇怪的行为,它在这里做了什么隐藏的事情?
提前感谢专家..
【问题讨论】:
-
我无法重现这一点,但您的线程函数
Func()没有return语句,这可能会给您带来未定义的行为。 -
您可能还想同步访问
std::cout。 -
@Galik:在添加 'return NULL;' 之后问题仍然出现。 Synchronize access 将按正确的顺序打印“text”和“endl”。但是在程序中我们只有两条'cout'语句,这两条语句打印'in main thread'、'endl'、'First thread execution'和'endl'。没有这4个同步序列可以是任何东西。但是在输出中我得到了额外的打印语句(即打印了六件事)。
标签: c++ multithreading pthreads