Simple windows thread example




















The following code is equivalent to the previous one. But this example is using WaitForMultipleObjects. The first parameter to the function call is the number of threads that are to be waited for. The second parameter is a pointer to the array of handles to these threads. The third parameter is a boolean. If true, it indicates that the function should return when all the threads are complete.

If false, it indicates the function should return on the completion of the first worker thread. The last parameter is the length of time that the master thread should wait before returning anyway. These resources need to be freed by calling the CloseHandle function on the handle to the thread. The following example demonstrates the complete sequence of creating a thread, waiting for it to complete, and then freeing its resources:.

A suspended thread is the one that is not currently running. Threads can be created in the suspended state and then started later. If a thread is in the suspended state, then the call to start the thread executing is ResumeThread. It takes the handle of the thread as a parameter. There is a SuspendThread call that will cause a running thread to be suspended.

This call is expected to be used only by tools such as debugger. Suspending a running thread may lead to problems if the thread currently holds resources such as mutexes. The following code demonstrates the creation of a suspended thread and then calling ResumeThread on that thread. The code uses a call to getchar , which waits for the enter key to be pressed, to separate the creation of the thread from the act of resuming thread:.

The suspended state of the thread is handled as a counter, so multiple calls to SuspendThread need to be matched with multiple calls to ResumeThread. Each thread of execution has associated with it a suspend count.

If this count is zero, then the thread is not suspended. If it is nonzero, the thread is in a suspended state. Each call to SuspendThread increments the suspend count. Each call to ResumeThread decrements the suspend count. A suspended thread will resume only when its suspend count has reached zero.

Therefore, to resume a suspended thread implies that there must be the same number of calls to ResumeThread as there have been calls to SuspendThread. Many of the Windows API functions return handles. As we saw from the earlier discussion of type casting, these are really just unsigned integers. However, they have a particular purpose.

Windows API calls that return handles have actually caused a resource to be created within the kernel space. Until Method2 is not completed its execution, Method3 is not going to be executed because of the sequential execution of the program i.

Note: Here we are not going to perform any database or Web Service call instead we can use the Thread class Sleep method to delay the execution of Method2 for 10 seconds.

Following is the signature of Sleep Method:. The sleep method takes the time in milliseconds as input and then suspends the current thread execution for that specified number of milliseconds. So, please modify the Program as shown below.

Now run the application and notice that the Method2 execution is delayed for 10 seconds. Once Method2 completes its execution then only Method3 start its execution. This is because all these three methods are executed by a single thread and this is the drawback of the single-threaded application. To solve the above problem, we are provided with a concept called Multithreading in C. As we already discussed Operating System has Processes which is used to run our applications. The Process contains Thread which will actually run our application code.

A process can have multiple threads and each thread can perform a different task. In simple words, we can say that the three methods we define in our program can be executed by three different threads. The advantage is that the execution takes place simultaneously. So when multiple threads trying to execute the application code, then the operating system allocates some time period to each thread to execute.

Now, in our example, we want to execute the three methods using three different threads let say t1, t2, and t3. The thread t1 is going to execute Method1, thread t2 is going to execute the Method2. At the same time, the Method3 is going to be executed by thread t3. Let us modify the Program as shown below to execute the methods with different Threads.

As you can see in the above code, we have created three different instances of Thread class. To the constructor of Thread class, we need to pass the method name which needs to be executed by that Thread.

Then we call the Start method on the Thread class which will start executing the method. Here the Main thread is going to create all other Threads.

Note: You will not get the output in a sequential manner. Run the application and see the output as shown below. The output may vary in your machine. Here, in this article, I try to explain the concept of Multithreading in C with Examples.

In the next article, I am going to discuss the Constructors of the Thread class. I hope you understood the basics for C Multithreading with Examples and enjoy this article. If the update thread alters the x coordinate and is preempted before it can change the y coordinate, the display thread might be scheduled before the y coordinate is updated.

The item would be displayed at the wrong location. You can avoid this problem by using semaphores to control access to the structure. A mutex short for mut ual ex clusion is a way of communicating among threads or processes that are executing asynchronously of one another.

This communication can be used to coordinate the activities of multiple threads or processes, typically by controlling access to a shared resource by locking and unlocking the resource. To solve this x , y coordinate update problem, the update thread sets a mutex indicating that the data structure is in use before performing the update. It would clear the mutex after both coordinates had been processed. The display thread must wait for the mutex to be clear before updating the display.

This process of waiting for a mutex is often called blocking on a mutex, because the process is blocked and cannot continue until the mutex clears. The Bounce. If ScreenMutex is clear, the wait function sets the mutex so other threads can't interfere with the display, and continues executing the thread. Otherwise, the thread blocks until the mutex clears.

When the thread completes the display update, it releases the mutex by calling ReleaseMutex. Screen displays and static data are only two of the resources requiring careful management.

For example, your program might have multiple threads accessing the same file. Because another thread might have moved the file pointer, each thread must reset the file pointer before reading or writing. In addition, each thread must make sure that it isn't preempted between the time it positions the pointer and the time it accesses the file. These threads should use a semaphore to coordinate access to the file by bracketing each file access with WaitForSingleObject and ReleaseMutex calls.

The following code example illustrates this technique:. All of an application's default stack space is allocated to the first thread of execution, which is known as thread 1. As a result, you must specify how much memory to allocate for a separate stack for each additional thread your program needs. The operating system allocates additional stack space for the thread, if necessary, but you must specify a default value.

The second argument specifies the default stack size for the thread. The last argument is an ID number that is passed to BounceProc. BounceProc uses the ID number to seed the random number generator and to select the thread's color attribute and display character. The C printf function requires more than bytes of stack space, and you should have 2K bytes of stack space available when calling Win32 API routines. Because each thread has its own stack, you can avoid potential collisions over data items by using as little static data as possible.

Design your program to use automatic stack variables for all data that can be private to a thread. The only global variables in the Bounce. Win32 also provides Thread-local storage TLS to store per-thread data. For more information, see Thread local storage TLS. There are several problems you might encounter in creating, linking, or executing a multithread C program.



0コメント

  • 1000 / 1000