Sleep()终止WindRiver中的线程

时间:2016-04-07 14:18:33

标签: c multithreading pthreads sleep wind-river-workbench

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

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

要杀死一个线程,我想等待确保它被创建,所以我发现我可以使用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()后,它就会被终止。

控制台日志:

  

在main中:在main中创建线程#0:在main中创建线程#1
:   创建线程#2
线程#0:随机:8
线程#1有效   现在要睡觉了。第2号线是活跃的并且正在睡觉   现在

睡觉后没有任何事情发生。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

通过拨打main()离开pthread_exit(),只退出&#34; main&#34;线程,否则结束main()结束进程并使用所有剩余的线程。

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