Alibaba 2014 school strokes (NanDa) -- Use thread and sleep to generate a pseudo-random string Sequence

Source: Internet
Author: User

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)


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.