我想了解semaphores
C++
如何运作,但我遇到了一些麻烦。
这是我的代码:
#include <iostream>
#include <pthread.h>
#include <fcntl.h> /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <semaphore.h>
using namespace std;
static sem_t *sem_thread;
static pthread_t thread_id;
void * threadFunc(void *) {
cout << "threadFunc\n";
cout << "threadFunc\n";
cout << "threadFunc\n";
cout << "threadFunc\n";
cout << "threadFunc\n";
sem_post(sem_thread);
return 0;
}
int main()
{
// Init semaphores
sem_thread = sem_open("./semaphores/sem_thread", O_TRUNC, 0777, 0);
// Init thread
int rc = pthread_create(&thread_id, NULL, threadFunc, NULL);
if (rc != 0)
{
cerr << "Pthread couldn't be created. rc=" << rc << endl;
abort();
}
sem_wait(sem_thread);
cout << "Main thread\n";
cout << "Main thread\n";
cout << "Main thread\n";
cout << "Main thread\n";
cout << "Main thread\n";
sem_close(sem_thread);
sem_unlink("./semaphores/sem_thread");
return 0;
}
所以我希望程序首先打印threadFunc
,然后打Main thread
。但是,这就是我得到的:
Main thread
tMhariena dtFhurneca
dt
hMraeiand Ftuhnrce
atdh
rMeaaidnF utnhcr
etahdr
eMaadiFnu ntch
rteharde
adFunc
知道发生了什么?
答案 0 :(得分:3)
您没有创建信号量,也没有检查它是否已创建。
致电sem_open
时出现两个问题:
O_CREAT
而不是O_TRUNC
来创建它。查看man sem_overview
,因此指定了命名约定:
命名信号量由表单名称/ somename标识; 也就是说,一个以空值终止的字符串,最多为NAME_MAX-4(即 251)由初始斜线组成的字符,后跟一个斜杠 或更多字符,其中没有一个是斜杠。