Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <windows.h>
- #include <stdio.h>
- #include <stdlib.h>
- #define DIM 1024
- char buffer[DIM];
- LPCTSTR nome = "EsempioSemaforo";
- HANDLE sem_t;
- DWORD WINAPI thread_function(PVOID arg) {
- LONG dwSemCount;
- HANDLE hSemaphore = OpenSemaphore( SYNCHRONIZE |
- SEMAPHORE_MODIFY_STATE, FALSE, nome );
- WaitForSingleObject( hSemaphore, INFINITE );
- while(strncmp("stop", buffer, 4) != 0) {
- printf("Ha inserito %d caratteri\n", strlen(buffer) -1);
- ReleaseSemaphore(hSemaphore, 1, &dwSemCount);
- WaitForSingleObject( hSemaphore, INFINITE );
- }
- ReleaseSemaphore(hSemaphore, 1, &dwSemCount);
- CloseHandle( hSemaphore );
- return 0;
- }
- int main() {
- HANDLE a_thread;
- DWORD a_threadId;
- DWORD thread_result;
- LONG dwSemCount;
- // Inizializza un semaforo.
- sem_t = CreateSemaphore( NULL, 0, 1, nome );
- if (sem_t == NULL) {
- perror("Inizializzazione del semaforo fallita");
- exit(EXIT_FAILURE);
- }
- // Crea un secondo thread.
- a_thread = CreateThread(NULL, 0, thread_function, (PVOID)NULL, 0,
- &a_threadId);
- if (a_thread == NULL) {
- perror("Creazione del thread fallita");
- exit(EXIT_FAILURE);
- }
- printf("Scrivi qualcosa ('stop' per uscire)\n");
- while(strncmp("stop", buffer, 4) != 0) {
- fgets(buffer, DIM, stdin);
- ReleaseSemaphore(sem_t, 1, &dwSemCount);
- WaitForSingleObject(sem_t, INFINITE);
- }
- printf("\nAttenti la fine del thread...\n");
- if (WaitForSingleObject(a_thread, INFINITE) != WAIT_OBJECT_0) {
- perror("Riunione thread fallita");
- exit(EXIT_FAILURE);
- }
- GetExitCodeThread(a_thread, &thread_result);
- printf("\nThread riuniti\n");
- exit(EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement