一个在C中停止另一个的线程

use*_*718 2 c c++ pthreads

我有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;
}
Run Code Online (Sandbox Code Playgroud)

例如,第一个线程必须停止第二个线程.怎么可能这样做?

Blu*_*kMN 10

通常,强制线程终止并不是一种好习惯.终止另一个线程的简洁方法是设置一个标志(两个线程都可见),告诉线程自行终止(通过立即返回/退出).