CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8
  1. #1
    Join Date
    Sep 2014
    Location
    Las Vegas, NV
    Posts
    85

    C++ Semaphore, limit 2 instances at the same time

    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.
    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 set the semaphore max value at 2 but it start all threads at same time instead of only 2.
    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

  2. #2
    2kaud's Avatar
    2kaud is online now Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: C++ Semaphore, limit 2 instances at the same time

    One way to do this could be
    Code:
    #include <stdio.h>
    #include <Windows.h>
    
    const int MAXTHREAD = 2;
    const int THREADS = 10;
    
    struct structure1 {
    	structure1(int th = 0) : threadnr(th) {}
    	int threadnr; 
    };
    
    DWORD WINAPI ThreadProc(LPVOID param)
    {
    structure1 *t1 = (structure1 *)param;
    
    	printf("Thread %i started\n", t1->threadnr);
    	Sleep(3000);
    	delete t1;
    	return 0;
    }
    
    HANDLE CreateThread(int th)
    {
    structure1 * t1 = new structure1(th);
    
    	return CreateThread(NULL, 0, ThreadProc, t1, NULL, NULL);
    }
    
    int main()
    {
    HANDLE hlds[MAXTHREAD] = {0};
    
    	for (int i = 0; i < THREADS; ++i) {
    		bool create = false;
    
    		for (int t = 0; (t < MAXTHREAD) && (create == false); ++t)
    			if (hlds[t] == 0) {
    				hlds[t] = CreateThread(i);
    				create = true;
    			}
    
    		if (create == false) {
    			DWORD result = WaitForMultipleObjects(MAXTHREAD, hlds, FALSE, INFINITE);
    			hlds[result - WAIT_OBJECT_0] = CreateThread(i);
    		}
    	}
    
    	WaitForMultipleObjects(MAXTHREAD, hlds, FALSE, INFINITE);
    	return 0;
    }
    PS I would consider using beginthreadex() rather than CreateThread(). See http://stackoverflow.com/questions/3...createthread-c
    Last edited by 2kaud; August 16th, 2015 at 05:30 AM. Reason: PS
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  3. #3
    Join Date
    Sep 2014
    Location
    Las Vegas, NV
    Posts
    85

    Re: C++ Semaphore, limit 2 instances at the same time

    2kaud - thank you for the code. it works exactly as i wanted
    I have only one confusion: i read that waitformultipleobject() can wait for maximum 64 objects so if i have 100 maxthreads and 500 threads it won't work ?
    Last edited by eclessiastes; August 15th, 2015 at 05:52 PM.

  4. #4
    VictorN's Avatar
    VictorN is online now Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: C++ Semaphore, limit 2 instances at the same time

    Quote Originally Posted by eclessiastes View Post
    ... i read that waitformultipleobject() can wait for maximum 64 objects so if i have 100 maxthreads and 500 threads it won't work ?
    Just read the WaitForMultipleObjects function article, section Remarks
    Victor Nijegorodov

  5. #5
    Join Date
    Nov 2000
    Location
    Voronezh, Russia
    Posts
    6,620

    Re: C++ Semaphore, limit 2 instances at the same time

    Quote Originally Posted by eclessiastes View Post
    I have only one confusion: i read that waitformultipleobject() can wait for maximum 64 objects so if i have 100 maxthreads and 500 threads it won't work ?
    C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Include\WinNT.h
    Code:
    #define MAXIMUM_WAIT_OBJECTS 64     // Maximum number of wait objects
    WaitForMultipleObjects function
    nCount [in]

    The number of object handles in the array pointed to by lpHandles. The maximum number of object handles is MAXIMUM_WAIT_OBJECTS. This parameter cannot be zero.
    Best regards,
    Igor

  6. #6
    Join Date
    Nov 2000
    Location
    Voronezh, Russia
    Posts
    6,620

    Re: C++ Semaphore, limit 2 instances at the same time

    Quote Originally Posted by eclessiastes View Post
    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.
    Frankly, I can see no point in having number of threads more than the number allowed to execute simultaneously.
    Best regards,
    Igor

  7. #7
    Join Date
    Sep 2014
    Location
    Las Vegas, NV
    Posts
    85

    Re: C++ Semaphore, limit 2 instances at the same time

    For some reason when i have
    [CODE]for (size_t i=0; i<10; ++i) [CODE]
    it doesn't show 1,2,3,4 etc but it appears random like 4,2,1,3,7,6,8,9
    is there any way to make it loop line by line instead of random ?

  8. #8
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: C++ Semaphore, limit 2 instances at the same time

    Rather than rolling your own thread pool, check out QueueUserWorkItem api in msdn.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured