【问题标题】:Close a thread when done with it完成后关闭线程
【发布时间】:2012-05-30 17:52:45
【问题描述】:

完成后如何关闭线程?比如确保没有任何东西是打开的或运行的?

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

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

【问题讨论】:

  • 顺便说一句,在您的示例中,当 main() 到达 return 0 时,您的整个程序将退出(包括您的 pthread)。
  • 没错,只是确保我使用的电量更少

标签: c++ c multithreading pthreads


【解决方案1】:

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

请注意,调用return 也会导致堆栈展开,并且在启动例程中声明的变量被销毁,因此它比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

【讨论】:

  • 哇,它吃得多,少得多的力量,做我需要的!谢谢丽豪! :D
  • 我从 int* arg = ptr; 得到“从 'void*' 到 'int* 的无效转换”,但是冰解释!
  • @user1417815:现在检查我的答案 :) 你得到一个错误,因为在 C++ 中需要类型转换,而在纯 C 中可以省略。
  • 所以返回比退出好?很好的解释和编码:)!非常感谢
  • @user1417815:是的,最好从启动例程返回而不是通过调用pthread_exit() 来终止它。请注意,当它返回时会隐式调用pthread_exit()。我也再次更新了我的答案。
【解决方案2】:

为此,您可以从线程函数 (multithreading1) 返回或调用 pthread_exit()

如需了解更多信息,请参阅POSIX Threads Programming

【讨论】:

  • 类似:pthread_exit(thread1)?或..请说明如何
  • @user1417815,在你的线程函数中。人 pthread_exit。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 1970-01-01
  • 2013-09-13
  • 2015-02-15
  • 2018-04-29
相关资源
最近更新 更多