【发布时间】:2012-02-29 11:59:29
【问题描述】:
我有 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;
}
例如,第一个线程必须停止第二个线程。 怎么可能做到这一点?
【问题讨论】: