I am trying to use POSIX in windows and use semaphores for synchronization of C and C++ programs.Since we are talking for separate programs, is this even possible? Or semaphores are only for sync in C/C++ files of the same program?
Asked
Active
Viewed 1,036 times
0
-
I'd try to use a library, like boost to help figure out Shared mem and locks with Windows. Check out this - they discuss some of what I think you are looking for http://www.boost.org/doc/libs/1_41_0/doc/html/interprocess/sharedmemorybetweenprocesses.html#interprocess.sharedmemorybetweenprocesses.sharedmemory.windows_shared_memory – Catalyst May 16 '15 at 20:48
-
in linux (and I suspect windows) a 'named semaphore' (the kind used to communicate between separate processes) is actually a file under the /proc file system. A 'named semnaphore' works very well for syncronization between different executables. – user3629249 May 18 '15 at 13:52
3 Answers
1
For communication between different programs, you need to use named semaphores. In POSIX Threads, the correct method to acquire a semaphore is : sem_open Just give a name to the semaphore, and use the same name in the programs which need to communicate.
See this answer for more details on how to do it: How to share semaphores between processes using shared memory
-
isn't sem_wait and sem_post like here: http://stackoverflow.com/questions/15182328/? – 101 May 16 '15 at 21:13
-
you use sem_open to create or open a shared semaphore. Then you use sem_post and sem_wait to use the semaphore (release and acquire respectively). – Seb May 17 '15 at 11:38
-
yes I know this applies in the case of POSIX but since I can only use the WIndows semaphores what are the equivalent commands in Windows for sem_wait and sem_post? – 101 May 17 '15 at 12:21
-
you have 2 solutions: either you use pthreads (POSIX Threads) in Win32, or you use the Win32 API. In the 1st case, you can use the mingw w64 compiler suite, and then use sem_open, sem_post, sem_wait, sem_close. In the 2nd case, you can use the following methods : CreateSemaphore/CreateSemaphoreEx/OpenSemaphore/ReleaseSemaphore/WairForSingleObject/WaitFor... Since you stated you wanted to use POSIX, the 1st solution seems natural. – Seb May 17 '15 at 18:57
-
actually I have to sync two processes and specifically the for loop of the first process with the for loop of the second process so how the code will look like with the Windows commands you provide? – 101 May 17 '15 at 19:20
0
Semaphores are members in Inter Process Communication tools. They can natively be used in C or C++ to synchronize different programs.

Serge Ballesta
- 143,923
- 11
- 122
- 252
0
For synchronization between seperate processes, a semaphore needs to be used.
See the following: Semaphores

SystemFun
- 1,062
- 4
- 11
- 21