c - Sleep() 终止 WindRiver 中的线程

标签 c multithreading pthreads sleep wind-river-workbench

我必须使用 WindRiver 用 C 编写一个小程序,它创建三个线程:

  • 线程 #1:创建一个随机数
  • 线程 #2:如果随机数小于 25,则杀死 #3
  • 线程 #3:如果随机数大于 25,则杀死 #2

要杀死一个线程,我想等待以确保它被创建,所以我发现我可以使用 sleep() 让另一个线程接管并让它自己创建。但他们都随着 sleep 而死去。

我想出了这段代码:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>    

#define NUM_THREAD 3

int theRandomNumber = 0;

void *RandomNumber (void *threadid){
    int id = (int) threadid;
    //srand();
    theRandomNumber = rand() % 50; 
    printf("Thread %d: Random: %d \n", id, theRandomNumber);
    pthread_exit(NULL);
    return 0;
}

void *CheckNumber (void *threadid){
  int id = (int) threadid;
  printf("Thread #%d is active and going to sleep now\n", id);
  sleep(1000);
  //here he dies without annoucing anything or something
  printf("Thread #%d is active again and back from sleep\n", id);
  if (id == 1){
      if (theRandomNumber >= 25){
          pthread_cancel(2);
          printf("THREAD %d: Thread #2 is closed \n", id);
      }
  }
  else{
      if (theRandomNumber < 25){
          pthread_cancel(1);
          printf("THREAD %d: Thread #1 is closed \n", id);
      }
  }
  return 0;
}


int main (int argc, char *argv[]){
  pthread_t threads[NUM_THREAD];
  int t = 0;

  printf("in main: create thread #%d \n", t);
  pthread_create (&threads[t], NULL, RandomNumber, (void *) t++);

  printf("in main: create thread #%d \n", t);
  pthread_create (&threads[t], NULL, CheckNumber, (void *) t++);

  printf("in main: create thread #%d \n", t);
  pthread_create (&threads[t], NULL, CheckNumber, (void *) t++);
}

带有 Randomnumber 的部分工作正常,我把它留在这里但我可以根据要求发布它。

线程到达 sleep() 后,它就会终止。

控制台日志:

in main: create thread #0
in main: create thread #1
in main: create thread #2
Thread #0: Random: 8
Thread #1 is active and going to sleep now
Thread #2 is active and going to sleep now

sleep 后什么也没有发生。有什么想法吗?

最佳答案

通过调用 pthread_exit() 离开 main(),只退出“主”线程,否则结束 main() 结束进程及其所有剩余的线程。

或者让 main() 通过对 pthread_create() 调用返回的每个 PThread-id 调用 pthread_join() 加入所有线程.

关于c - Sleep() 终止 WindRiver 中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36478988/

相关文章:

c - pthread_mutex_unlock 不是原子的

c - 如何检查目录是否存在?

c - c语言获取和检查字符串

c++ - 如何在 Linux 上的新终端上执行新线程?

c - 在 c 中使用带套接字的线程

c++ - pthreads_create() 返回非零值?

c - 将结构中的指针设置为 null

c - 如何在 C 中的标准输入上使用 fgets() 而不是 fscanf()?

c# - WPF:在 UI 线程和后台线程之间传递对象

java - 在java中向桌面应用程序发送推送通知