Introduction:
Apart from the first character (subscript 0), create a thread for each of the other N-1 characters, each thread first sleep one second (can also be longer ), then swap the character at the corresponding position with the first character; after the N-1 threads are completed, the main thread ends. The principle is hidden in the question. One second after sleep,Because of the inaccuracy of sleep, this N-1 thread almost wakes up at the same time (ready) (imagine if sleep is very accurate, the order of waking of each thread will be the same as the order of creation ); due to the randomness of thread scheduling, the thread that will be executed is random, (I do not know the order) the Exchange described before the execution of the N-1 is a pseudo random sequence.However, I couldn't remember the sequence of pthread_create parameters (the calculation workload of the previous question was not small, and the headers were all confused), so I wrote them in order. After I came back, I quickly wrote the following on my computer:
Wait for other threads to make the writing simple and not rigorous!
Note that count is also a critical resource and needs to be placed in the critical zone (the same as str [0 ); in addition, the mutex required by the pthread_cond_wait interface cannot be used to maintain the "other threads" critical. Another mutex should be defined. Pthread_cond_wait will atomically block the mutex passed in by the current thread at the same time by unlock. When pthread_cond_wait returns, the imported mutex will be locked again. (APUEcn2e p309)
Note: Local Environment gcc 4.6.1 (MinGW)