关键区域中有多个线程

时间:2019-05-05 16:50:37

标签: c linux pthreads semaphore

我有一个必须创建15个线程的进程,每个线程应显示其开始和结束。在任何时候,最多可能有5个线程正在运行,并且ID为7的线程仅在其他5个线程(包括自身)正在运行时才必须显示其结束(正在运行意味着它们已经显示了开始消息,但未显示结束消息) 。我尝试使用3个信号灯来做到这一点:一个信号灯在关键区域最多允许5个线程,一个信号灯阻塞ID为7的线程的结束,另一个信号灯验证其他4个线程是否正在运行并解锁阻塞线程7的信号灯。我被卡住了,我不知道如何验证其他4个线程是否正在运行。

players = int(input("Enter players:"))
home = [int(players) for players in input("Enter home team runs: ").split()]
print(home)

1 个答案:

答案 0 :(得分:0)

  

我不知道如何验证其他4个线程是否正在运行。

您可以为此使用两个信号量:

  1. 信号量M,用作互斥量并保护线程计数器免受并发修改。
  2. 信号量N4,仅在运行线程数为4时打开,并在其他所有时间均关闭。

初始化:

sem_M = sem_open("sem1",O_CREAT,0644,1);
sem_N4 = sem_open("sem1",O_CREAT,0644,0);
// Number of running threads. Do not count thread 7.
int n_threads_running = 0;

普通线程可以按以下方式工作:

// Beginning
sem_wait(sem_M);

if(n_threads_running == 4) {
  // Number of threads is changing from 4 to non 4. Close the semaphore.
  sem_wait(sem_N4);
}

n_threads_running ++;

printf("BEGIN %d \n",*nrth);

if(n_threads_running == 4) {
  // Number of threads has been changed from non 4 to 4. Open the semaphore.
  sem_post(sem_N4);
}

sem_post(sem_M);

// Ending

sem_wait(sem_M);
if(n_threads_running == 4) {
  // Number of threads is changing from 4 to non 4. Close the semaphore.
  sem_wait(sem_N4);
}

n_threads_running --;

printf("END %d \n",*nrth);

if(n_threads_running == 4) {
  // Number of threads has been changed from non 4 to 4. Open the semaphore.
  sem_post(sem_N4);
}

sem_post(sem_M);

线程7可以按以下方式工作:

// Beginning
printf("BEGIN %d \n",*nrth);

// Ending. Wait until number of other running threads become 4.
sem_wait(sem_N4);
// Print ending message
printf("END %d \n",*nrth);
// Now restore the semaphore, so the number of threads may be changed again.
sem_post(sem_N4);

使用两个信号量时,不可能出现死锁:与其他线程不同,线程7仅使用这些信号量之一。