2017-02-14 32 views
0
#include <pthread.h> 
#include <iostream> 

using namespace std; 

void OnCreateThread() 
{ 
    cout << "Create a thread." << endl; 
} 

void OnExitThread() 
{ 
    cout << "Exit a thread." << endl; 
} 

void f(void*) {} 

int main() 
{ 
    // 
    // What to do here ??? 
    // 
    pthread_t dummy; 
    pthread_create(&dummy, 0, f, 0); 
    pthread_create(&dummy, 0, f, 0); 
    while (true); 
} 

的代码创建了两个原生线程,比std::thread其他的,我希望它输出如下:如何调用线程创建和退出的函数?

Create a thread. 
Create a thread. 
Exit a thread. 
Exit a thread. 

它可以在Windows下使用FlsXXX函数来完成。

但是,我不知道它是否也可以在Linux下完成。

在Linux下有没有标准的方法?

+0

你想知道如何使用'pthread_create'或者你想知道如何得到你想要的输出吗? – Chad

+0

您将在[pthreads(7)手册页](http://manpages.courier-mta.org//htmlman7/pthreads.7.html)中找到记录的所有线程函数。如果它没有记录在那里,它不存在。从字面上看,这里的答案是RTFM。 –

+0

如果你不能注册这些函数,你仍然可以影响pthread_create。我只是在开玩笑... – felix

回答

1

如何调用线程的创建和退出函数?

Pthreads API不为线程创建提供回调(也不提供std::thread API)。

但是解决方案很简单:在start_routine回调的开头和结尾调用函数。

void* f(void*) { 
    OnCreateThread(); 
    OnExitThread(); 
    return nullptr; 
} 

万一你可能想OnExitThread甚至当线程已经提前终止被调用,您可能需要使用pthread_cleanup_push将其注册为一个回调。


PS。 start_routine回调必须返回void*

1

至少存在一个pthread_cleanup_push函数,它允许您添加一个将在线程终止后立即调用的函数。从来没有听说过创作相同,但一些API可能有这样的。