我必须编写一个多线程(比如2个线程)程序,其中每个线程执行不同的任务.此外,这些线程一旦启动就必须在后台无限运行.这就是我所做的.有人可以给我一些反馈,如果方法是好的,如果你看到一些问题.另外,我想知道如果用Ctrl + C终止执行,如何以系统的方式关闭线程.
main函数创建两个线程,让它们无限运行,如下所示.
这是骨架:
void *func1();
void *func2();
int main(int argc, char *argv[])
{
pthread_t th1,th2;
pthread_create(&th1, NULL, func1, NULL);
pthread_create(&th2, NULL, func2, NULL);
fflush (stdout);
for(;;){
}
exit(0); //never reached
}
void *func1()
{
while(1){
//do something
}
}
void *func2()
{
while(1){
//do something
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
使用答案中的输入编辑代码: 我是否正确退出线程?
#include <stdlib.h> /* exit() */
#include <stdio.h> /* standard in and output*/
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <signal.h>
#include <semaphore.h>
sem_t end; …
Run Code Online (Sandbox Code Playgroud)