Hello
I'm trying to make a loop create 10 threads but only 2 working threads at the same time, wait until one finish the job then start another thread but never exceed 2 at same time. I'm doing this with semaphores.
I set the semaphore max value at 2 but it start all threads at same time instead of only 2.Code:#include <iostream> #include <Windows.h> typedef struct structure1 { int threadnr; } structure1; HANDLE ghSemaphore = CreateSemaphore(NULL, 2, 2, NULL); DWORD WINAPI ThreadProc(LPVOID param) { structure1 * t1 = (structure1 *)param; printf("Thread %i\n",t1->threadnr); Sleep(1000); return 0; } int main() { for (int i = 0; i < 10; i++) { WaitForSingleObject(ghSemaphore, INFINITE); structure1 * t1 = new structure1; t1->threadnr = i; CreateThread(NULL, 0, ThreadProc, t1, NULL, NULL); ReleaseSemaphore(ghSemaphore, 1, 0); } system("PAUSE"); return 0; }
I tried to set WaitForSingleObject at the beginning of ThreadProc and ReleaseSemaphore at the end and it works but it will create all threads in buffer. I want to create just 2 at same time and wait for one to finish then start another one
Any idea ?
Thank you




Reply With Quote
