【问题标题】:A thread that stops another one in C在 C 中停止另一个线程的线程
【发布时间】: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;
}

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

【问题讨论】:

    标签: c++ c pthreads


    【解决方案1】:

    通常强制线程终止不是一个好习惯。终止另一个线程的干净方法是设置一个标志(对两个线程可见),告诉线程终止自身(通过立即返回/退出)。

    【讨论】:

      【解决方案2】:

      这听起来像是非常复杂(糟糕)的设计。通常你会有一个主人(控制器),它会有孩子。

      如果你必须采用这种方法,我会让第一个线程产生第二个,然后第二个产生第三个(这样它就“拥有”那个线程)。

      最后,如果你必须这样做,你可以通过它的 void* 参数将线程传递给第一个工人。

      另外,您不需要显式退出线程,只需让它“运行”然后加入即可。

      【讨论】:

        【解决方案3】:

        将另一个线程的 id 作为参数传递给 2 个线程。在完成工作的第一个电话pthread_kill(other_thread_id, SIGKILL)。我假设你知道你在做什么(你已经被警告过这是不好的做法)。

        【讨论】:

        • 在旧的拨号连接中,经常会出现连接卡住的情况,而摆脱这种情况的唯一可能方法是终止应用程序。如果您有可能关闭连接(即使来自其他线程),则无需终止程序本身。只有当它成为一种习惯时,这才是糟糕的。
        【解决方案4】:

        查看方法pthread_cancel()取消(结束)一个线程。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-09-29
          • 1970-01-01
          相关资源
          最近更新 更多