c/c++语言开发共享完成后关闭线程

你什么时候关闭线程怎么样? 比如确保什么都没有打开或跑步?

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

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: %dn", iret1); } return 0; } 

    “当你完成时,你如何关闭一个线程?”
    通过简单地从该函数返回或调用pthread_exit函数 。

    请注意,调用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. 

    有关更多信息,请参阅pthread启动函数中的return()与pthread_exit()

    “确保没有任何东西可以打开或运行”
    您应该使用pthread_join函数等待终止,而不是确定您的线程是否仍在运行。

    这是一个例子:

     void *routine(void *ptr) { int* arg = (int*) ptr; // in C, explicit type cast is redundant printf("changing %d to 7n", *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 %dn", *retval); return 0; } 

    产量

     changing 3 to 7 thread1 returned 7 

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

    有关更多信息,请参阅POSIX线程编程 。

      以上就是c/c++开发分享完成后关闭线程相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/545562.html

      (0)
      上一篇 2021年1月10日
      下一篇 2021年1月10日

      精彩推荐