c - 以延迟取消结束 pthread

标签 c multithreading pthreads signals mutex

我是 pthreads 和信号处理的新手,我正在从事一个项目,该项目将创建 x 数量的 pthreads 作为生产者或消费者,永远执行,我想结束所有threads 然后是 main 以系统的方式。

为此,我尝试使用信号处理程序捕获 ^c,然后设置一些全局标志以结束线程。

我已尝试执行以下操作,但我不确定它是否有效,我希望获得有关我的思考过程和实现的建议。

这是我正在使用的,省略了错误检查:

#include stdio, pthread, stdlib, semaphore, time, string, unistd, signal

sem_t empty, full;
pthread_mutex_t mutex;
int flag = 0;
void *producer();
void *consumer();
void sig_handler(int sig);

int main(int argc, char *argv[]){

   signal(handler(SIGINT, sig_handler);

   //init locks and semas
   pthread_mutex_init(&mutex, NULL);
   sem_init(&empty, 0, SOME_BUFFER_SIZE);
   sem_init(&full, 0, 0);

   pthread_t prod_threads[5]; //5 for example, can be any amount passed in
   pthread_t cons_threads[3];

   //start up threads
   for(i = 0; i < 5; i++)
      pthread_create(&prod_threads[i], NULL, producer, NULL)
   for(i = 0; i < 3; i++)
      pthread_create(&cons_threads[i], NULL, consumer, NULL)

   //join threads at end
   for(i = 0; i < PROD; i++)
     pthread_join(&prod_threads[i], NULL);

   for(i = 0; i < CONS; i++)
     pthread_join(&cons_threads[i], NULL);

   sleep(4);//could be any amount of time
   exit(EXIT_SUCCESS);

}
//not sure if I am going about this the right way
void sig_handler(int sig){
  if(sig == SIGINT)
    flag = 1;

}

void *producer(){
  while(1){
    sleep(x);//where x is some random time

    //part I am concerned about:
     if(flag)
      exit(EXIT_SUCCESS);
    //get locks and semaphore stuff
    //enter crit section
    //release locks, semaphore
  }
 void *consumer(){
   while(1){
      sleep(x);//sleep some random time

      //again not sure if this is right or not
      if(flag)
        exit(EXIT_SUCCESS);
      //get locks
      //enter crit
      //release locks
  }



 }
}

我的程序似乎可以正常执行,我只是不确定我是否正确使用了 pthreads 和信号,并希望获得一些指导。如果您需要更完整的代码,请告诉我

谢谢

最佳答案

你的执行似乎是合适的,但是使用@yano 提供的文档,你的pthread_join() 有点偏离。

代替:

for(i = 0; i < PROD; i++)
 pthread_join(&prod_threads[i], NULL);

for(i = 0; i < CONS; i++)
 pthread_join(&cons_threads[i], NULL);

你需要:

for(i = 0; i < PROD; i++)
 pthread_join(prod_threads[i], NULL);

for(i = 0; i < CONS; i++)
 pthread_join(cons_threads[i], NULL);

注意和号。我不确定这是否是您要找的东西,但希望对您有所帮助。

关于c - 以延迟取消结束 pthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36392118/

相关文章:

ios - NSRunLoop运行模式:beforeDate: doesn't wait

c++ - 将 C++ 函数对象作为线程例程传递给 pthread_create 函数

c++ - 如何在 C++ 中使用 pthread 将数据从一个线程传递到另一个正在运行的线程

c - 将结构作为值参数传递给线程

c - 通过个人源码打开图表软件(ninjatrader)

c++ - 使用混合 C/C++ header 在 C 中使用 C++ 对象

c - C 函数可能的返回类型

更改 Win32 Windows 项目中的默认窗口字体

python - 运行时错误: threads can only be started once for a beginner

Posix 线程的条件变量