我有2个线程。
我的目标是终止自己执行的第一个线程必须停止另一个线程。
可能吗?
我有以下代码:
#include <stdio.h>
#include <pthread.h>
#include <sys/types.h>
void* start1(void* arg)
{
printf("I'm just born 1\n");
int i = 0;
for (i = 0;i < 100;i++)
{
printf("Thread 1\n");
}
printf("I'm dead 1\n");
pthread_exit(0);
}
void* start2(void* arg)
{
printf("I'm just born 2\n");
int i = 0;
for (i = 0;i < 1000;i++)
{
printf("Thread 2\n");
}
printf("I'm dead 2\n");
pthread_exit(0);
}
void* function()
{
int k = 0;
int i = 0;
for (i = 0;i < 50;i++)
{
k++;
printf("I'm an useless function\n");
}
}
int main()
{
pthread_t t, tt;
int status;
if (pthread_create(&t, NULL, start1, NULL) != 0)
{
printf("Error creating a new thread 1\n");
exit(1);
}
if (pthread_create(&tt, NULL, start2, NULL) != 0)
{
printf("Error creating a new thread 2\n");
exit(1);
}
function();
pthread_join(t, NULL);
pthread_join(tt, NULL);
return 0;
}
例如,第一个线程必须停止第二个线程。
怎么可能做到这一点?
最佳答案
通常,强制终止线程不是一个好习惯。终止另一个线程的一种干净方法是设置一个标志(对两个线程都可见),该标志告诉线程终止自身(立即返回/退出)。