c++ - 完成后关闭线程

标签 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;
}

最佳答案

“完成后如何关闭线程?”
通过简单地从该函数返回或调用 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

关于c++ - 完成后关闭线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10821618/

相关文章:

c++ - 编译 C++ 模板代码时出现问题

c - 返回指针的函数声明

python - c 程序 SWIG 到 python 给出 'ImportError: dynamic module does not define init function'

c++ - 生产者和消费者优化

如果线程结束,Java Thread.join() 方法将卡住

Java:线程缓存

c++ - multimap 与next_permutation C++的结合使用

c++ - 关于 protected 成员函数和派生类访问的混淆

c++ - 使用模板调用重载函数(unresolved overloaded function type compiler error)

c - 什么是 "Signal 15 received"