线程执行:如何确保线程的系统启动

时间:2015-05-15 07:38:56

标签: linux-kernel pthreads scheduler

我看到了在ubuntu和其他Linux平台上启动线程的不同方法。

pthread_create ( &thread1, NULL, (void *) &myfun1, (void *) msg1);
pthread_create ( &thread2, NULL, (void *) &myfun2, (void *) msg2);
pthread_create ( &thread3, NULL, (void *) &myfun3, (void *) msg3);
pthread_create ( &thread4, NULL, (void *) &myfun4, (void *) msg4);

在上面的ubuntu的情况下,首先是thread4正在启动,而在其他linux os的情况下,它是thread1。当我检查原因时,似乎是因为调度政策(如果我错了,请纠正我)。

  1. 在这些情况下,如何确保始终第一个线程(thread1)首先执行,尽管Linux风格不同。

  2. / 通用查询 /,调度策略不依赖于内核吗?因为在不同的linux风格中可以看到两种不同类型的线程执行。

1 个答案:

答案 0 :(得分:0)

使线程1在另一个线程执行任务之前启动的伪代码:

Mutex mutex = ... /* static init here */
Condition cond = ... /* static init here */

boolean first_thread_running = false;

thread1
{
  mutex_lock

  first_thread_running = true;
  cond_signal

  mutex_unlock

  /* do things */
}

thread<N> /* with <N> = {2, 3, 4} */
{
  mutex_lock

  while (not first_thread_running)
    cond_wait

  mutex_unlock

  /* thread1 definitly runs now */

  /* do things */
}    


main
{
  /* The order of the following statements does not matter, thread 1
     will always be started before the other threads "do their things". */

  thread4_create
  thread2_create
  thread1_create
  thread3_create

  ...