完成后关闭线程

时间:2012-05-30 17:52:46

标签: c++ c multithreading pthreads

完成后如何关闭线程?比如确保什么都没有打开或跑步?

到目前为止,我知道如何打开它,但是......不是如何正确地关闭它

int  iret1; 
pthread_t thread1;
char *message1;

void *multithreading1( void *ptr ) {
    while (1) {
        // Our function here
    }   
}

int main (int argc, char * const argv[]) {
    if( (iret1=pthread_create( &thread1, NULL, multithreading1, (void*) message1)) )
    {
        printf("Thread creation failed: %d\n", iret1);
    }
    return 0;
}

2 个答案:

答案 0 :(得分:7)

要执行此操作,您可以从线程函数(multithreading1)返回或致电pthread_exit()

有关详细信息,请参阅POSIX Threads Programming

答案 1 :(得分:7)

“完成后如何关闭线程?”
通过简单地从该函数返回或调用pthread_exit function

请注意,调用return也会导致堆栈被展开,并且在start例程中声明的变量将被销毁,因此它比pthread_exit函数更可取:

An implicit call to pthread_exit() is made when a thread other than the thread in
which main() was first invoked returns from the start routine that was used to
create it. The function's return value shall serve as the thread's exit status.

有关更多信息,请查看:return() versus pthread_exit() in pthread start functions

“确保不再打开任何内容或正在运行”
您不应确定您的线程是否仍在运行,而应使用pthread_join function等待终止。

这是一个例子:

void *routine(void *ptr) {
    int* arg = (int*) ptr; // in C, explicit type cast is redundant
    printf("changing %d to 7\n", *arg);
    *arg = 7;
    return ptr;
}

int main(int argc, char * const argv[]) {
    pthread_t thread1;
    int arg = 3;
    pthread_create(&thread1, NULL, routine, (void*) &arg);

    int* retval;
    pthread_join(thread1, (void**) &retval);
    printf("thread1 returned %d\n", *retval);
    return 0;
}

输出

changing 3 to 7
thread1 returned 7