Search code examples
cwindowsmultithreadingwinapithread-synchronization

Can two Threads use same Thread Procedure?


Is it possible for two threads to use a single function "ThreadProc" as its thread procedure when CreateThread() is used?

HANDLE thread1= CreateThread( NULL, //Choose default security
                              0, //Default stack size
                              (LPTHREAD_START_ROUTINE)&ThreadProc,
                              //Routine to execute. I want this routine to be different each time as I want each  thread to perform a different functionality.
                              (LPVOID) &i, //Thread parameter
                              0, //Immediately run the thread
                              &dwThreadId //Thread Id
                            ) 
HANDLE thread2= CreateThread( NULL, //Choose default security
                              0, //Default stack size
                              (LPTHREAD_START_ROUTINE)&ThreadProc,
                              //Routine to execute. I want this routine to be different each time as I want each  thread to perform a different functionality.
                              (LPVOID) &i, //Thread parameter
                              0, //Immediately run the thread
                              &dwThreadId //Thread Id
                            ) 

Would the above code create two threads each with same functionality(since thread procedure for both of the threads is same.) Am I doing it correctly?

If it is possible then would there be any synchronization issues since both threads are using same Thread Procedure.

Please help me with this. I am really confused and could not find anything over the internet.


Solution

  • It is fine to use the same function as a thread entry point for multiple threads.

    However, from the posted code the address of i is being passed to both threads. If either thread modifies this memory and the other reads then there is a race condition on i. Without seeing the declaration of i it is probably a local variable. This is dangerous as the threads require that i exist for their lifetime. If i does not the threads will have a dangling pointer. It is common practice to dynamically allocate thread arguments and have each thread free its arguments.