As the amount of processing data increases gradually, the serial single-core program, like a residual lamp missing months, can not meet the needs of the application.
The emergence of large-scale clusters. Overcome this technical problem. The purpose of this paper is to explore how to use multi-CPU parallel programming, which is described in the previous article on Cuda. The structure of this paper is divided into three parts. The first part gives a piece of code, simulates the procedure of selling train tickets; the second part explains the procedure and facilitates the exchange of learning. The third part gives the result of the program. First, the program code
Second, the code explanation
This program uses two threads to sell 100 tickets, in order to ensure synchronization. Mutually exclusive objects are used.
A declaration of two thread entry functions. Define the total number of train tickets and the index of the sold train ticket, and finally create a global variable to hold the handle of the mutually exclusive object.
Apply two handle variables. Represents a pointer to a thread, creates a mutually exclusive object, and three parameters are: the security structure pointer (null represents the default security), the initial owner of the mutually exclusive object (false means no), the name of the mutually exclusive object (null means default), and the last use of CreateThread Create two threads, six parameters are: security structure pointer (null for default security), set initial stack size, entry function pointer. The number of parameters to the new thread function. A token created by the control thread (0 means run immediately after creation), and the return value is used to receive the thread ID;
Closes the handle to the new thread, but does not terminate the created thread; then sleeps for 400 milliseconds;
Thread 1 entry function, enter the while loop, first using WaitForSingleObject(hmutex,INFINITE requests for mutually exclusive objects, and then runs the pediatric program, finally releasing mutually exclusive objects, who have mutually exclusive objects who are released, thus guaranteeing a simultaneous access to global variables. Thread 2 is the same.
OK, the content of this section is complete! iii. Results of implementation
Visual Studio 2010 Multi-threaded programming