Multithreading 信号量不工作C++;

Multithreading 信号量不工作C++;,multithreading,c++11,semaphore,Multithreading,C++11,Semaphore,我对信号量不太熟悉,试图写一个非常基本的例子来更好地学习它。我的代码有三个数组: b1[5]={1;2;3;4;5} b2[5]={6;7;8;9;10} x[10] 我有一个函数,它接受b1或b2并更新x,如下所示: x={0;1;2;3;4;5;6;7;8;9} 我的代码如下: #include <sys/types.h> /* Primitive System Data Types */ #include <errno.h> /* Errors

我对信号量不太熟悉,试图写一个非常基本的例子来更好地学习它。我的代码有三个数组:

b1[5]={1;2;3;4;5}
b2[5]={6;7;8;9;10}
x[10]
我有一个函数,它接受b1或b2并更新x,如下所示:

x={0;1;2;3;4;5;6;7;8;9}
我的代码如下:

#include <sys/types.h>  /* Primitive System Data Types */ 
#include <errno.h>      /* Errors                      */
#include <stdio.h>      /* Input/Output                */
#include <stdlib.h>     /* General Utilities           */
#include <thread>       /* C++11 Threads               */
#include <string.h>     /* String handling             */
#include <semaphore.h>  /* Semaphore                   */
#include <Windows.h>    /* windows                     */
using namespace std;

/* prototype for thread routine */
void handler(int x[], int b[], int start, int id);

/* global vars */
sem_t mutex;
vector<std::thread> threadList;

int main()
{
int i[2];
int x[10];
int b1[5];
int b2[5];
sem_init(&mutex, 0, 1);      /* initialize mutex to 1 - binary semaphore     */
/* second param = 0 - semaphore is local */
i[0] = 0;
i[1] = 1;

    // Update the matrix
    for (int j = 0; j < 5; j++)
    {
        b1[j] = j;
        b2[j] = j+5;
    }



        threadList.push_back(std::thread(handler, x, b1, 0, 0));
        threadList.push_back(std::thread(handler, x, b2, 5, 1));

        // wait for all threads to finish
        for (auto& threadID : threadList){
            threadID.join();
        }

sem_destroy(&mutex); /* destroy semaphore */

/* exit */
return 0;
} /* main() */

void handler(int x[], int b[], int start, int id)
{

    for (int j = start; j < 5; j++)
    {
        x[j] = b[j];
     }
    printf("Thread %d: Waiting to print results...\n", id);
    sem_wait(&mutex);       /* down semaphore */
    /* START CRITICAL REGION */
    for (int j = start; j < 5; j++)
    {
        printf("x[%d] = %d\n", j , x[j]);
    }
    /* END CRITICAL REGION */
    sem_post(&mutex);       /* up semaphore */
}
Thread 0: Waiting to print results...
x[0] = 0
x[1] = 1
x[2] = 2
x[3] = 3
x[4] = 4
Thread 1: Waiting to print results...
然而,我期待着如下的事情

Thread 0: Waiting to print results...
x[0] = 0
x[1] = 1
x[2] = 2
x[3] = 3
x[4] = 4
Thread 1: Waiting to print results...
x[5] = 5
x[6] = 6
x[7] = 7
x[8] = 8
x[9] = 9

知道为什么第二个线程没有进入代码的打印部分吗?

您对“handler”的第二次调用的start=5

环路

for (int j = start; j< 5; j++)
for(int j=start;j<5;j++)

不是在两个位置都执行,因为j>=5。

您使用的是什么信号量实现?在同一个代码中看到
semu t
#include
非常奇怪。我使用的是#include中的一个。这部分代码中没有真正使用windows.h include。您在windows上吗?Windows提供了
CreateSemaphore
。您的
sem_init
必须来自第三方提供商。这就是为什么我问什么是实现。头文件的名称不能回答这个问题。是的,我在Windows上。既然不是操作系统提供的,那么您使用的是什么信号量实现?