多线程启动订单 [英] multithread launching order

查看:134
本文介绍了多线程启动订单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个线程来创建线程1,线程,thread3和thread4:

I have 4 threads to create thread1, thread2, thread3 and thread4:

pthread_create(thread1,NULL,thread_func1,NULL);
pthread_create(thread2,NULL,thread_func2,NULL);
pthread_create(thread3,NULL,thread_func3,NULL);
pthread_create(thread4,NULL,thread_func4,NULL);

寻找在调试,如在源$ C ​​$ C定义启动的线程的顺序是不一样的。
是否有启动线程与订单,我可以定义一个解决方案?

looking in the debug , The order of launched threads is not the same as defined in the source code. Are there a solution to launch the threads with an order that I could define?

推荐答案

在这里我使用的解决方案后,

here after the solution I used

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

static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static bool wait = TRUE;

void thread_sync() {
  pthread_mutex_lock(&mut);
  wait = FALSE;
  pthread_cond_signal(&cond);
  pthread_mutex_unlock(&mut);
}
void thread_wait_sync() {
  pthread_mutex_lock(&mut);
  if (wait==TRUE)
  {
      pthread_cond_wait(&cond,&mut);
  }
  wait = TRUE;
  pthread_mutex_unlock(&mut);
}

void *thread1(void *d) {
  thread_sync();
  while (1); // Rest of work happens whenever
  return NULL;
}

void *thread2(void *d) {
  thread_sync();
  while (1);
  return NULL;
}

void *thread3(void *d) {
  thread_sync();
  while (1);
  return NULL;
}

void *thread4(void *d) {
  while (1);
  return NULL;
}

int main() {
  pthread_t t1,t2,t3,t4;
  pthread_create(&t1, NULL, thread1, NULL);
  thread_wait_sync();
  pthread_create(&t2, NULL, thread2, NULL);
  thread_wait_sync();
  pthread_create(&t3, NULL, thread3, NULL);
  thread_wait_sync();
  pthread_create(&t4, NULL, thread4, NULL);
  while(1) {
    // some work
  }
}

这篇关于多线程启动订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆