Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何终止无限循环(线程)_C_Multithreading_Pthreads - Fatal编程技术网

C 如何终止无限循环(线程)

C 如何终止无限循环(线程),c,multithreading,pthreads,C,Multithreading,Pthreads,我对退出while循环有疑问。我正在编写代码,其中我创建了两个线程,它们打印字符串,main()部分必须每500毫秒打印一次点(“.”)。您能否帮助我如何在第二个线程终止后退出while循环,以便在输出时获得类似的结果: ……你好……世界……结束了 谢谢你的帮助 int main() { int mls = 0.5 ; pthread_t thread1; pthread_t thread2; struktura param1 = { "Hello", 2}

我对退出while循环有疑问。我正在编写代码,其中我创建了两个线程,它们打印字符串,main()部分必须每500毫秒打印一次点(“.”)。您能否帮助我如何在第二个线程终止后退出while循环,以便在输出时获得类似的结果: ……你好……世界……结束了

谢谢你的帮助

int main() 
{
    int mls = 0.5 ; 
    pthread_t thread1;
    pthread_t thread2;

    struktura param1 = { "Hello", 2};
    struktura param2 = { "World", 4};

    pthread_create( &thread1, NULL, thread, &param1);
    pthread_create( &thread2, NULL, thread, &param2);

    while(1)
    {
        printf(".");
        fflush(stdout);
        sleep(mls); 
    }

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    printf("THE END\n");
    return 0;
}

尝试使用pthread_exit,如中所示

int pthread_kill(pthread_t thread,int sig)

您可以使用此函数检索线程的状态,如果sig参数为0,则不会发送任何信号,但仍会执行错误检查(例如,您可以使用此函数检查线程是否“活动”)。


它可以返回0或错误代码(ESRCH-找不到ID为thread的线程,在这种情况下,还有一个线程不重要),如果返回值为0,则线程为“活动”,如果返回值为错误代码(ESRCH),则指定的线程无法找到,例如,它为“死线程”。

在考虑了问题后,我得出的结论是,如果主要用例真的要确保两个线程(线程“Hello”和线程“World”)都消失了,那么就没有其他方法在这两个线程上都使用
pthread\u join()

由于
pthread\u join()
阻塞了调用线程,因此自然的结论是启动第三个线程(线程“Dots”)来根据请求绘制点


然后,第三个线程(线程“点”)由
main()
-线程发出信号,等待其他两个线程(线程“Hello”和线程“World”)在从对
pthread\u join()的两个阻塞调用返回后完成。如果这样做了,第三条线(线“点”)就完成了。后者可以独立运行,因为没有人在等待它终止

如果我理解正确,函数pthread_exit将退出线程处理,但如果thread2已结束,我需要在while循环中进行检查,然后中断循环。
pthread_exit()
在任何情况下都无助于解决OP的问题。“int mls=0.5”?0.5不是整数。这适用于这种特殊情况。如果在同一个进程中创建、运行、终止更多线程,并且与此问题无关,那么它可能不再工作,因为pthread id被回收。因此,
thread1
和/或
thread2
的值很可能在两个
之间重用,而
则由一个或两个独立运行的任务进行测试。更安全的解决方案是为每个线程使用一个条件/互斥体,作为停止前的最后一个任务来表示其终止。
 while(pthread_kill(thread1, 0) == 0 &&  pthread_kill(thread2, 0) == 0)
 {
      printf(".");
      fflush(stdout);
      sleep(mls); 
 }