Starting with pthreads, I cannot understand what is the business with pthread_key_t and pthread_once_t?
Would someone explain in simple terms with examples, if possible?
thanks
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
No, it can’t be explained in layman terms. Laymen cannot successfully program with pthreads in C++. It takes a specialist known as a “computer programmer” 🙂
pthread_once_tis a little bit of storage whichpthread_oncemust access in order to ensure that it does what it says on the tin. Each once control will allow an init routine to be called once, and once only, no matter how many times it is called from how many threads, possibly concurrently. Normally you use a different once control for each object you’re planning to initialise on demand in a thread-safe way. You can think of it in effect as an integer which is accessed atomically as a flag whether a thread has been selected to do the init. But sincepthread_onceis blocking, I guess there’s allowed to be a bit more to it than that if the implementation can cram in a synchronisation primitive too (the only time I ever implementedpthread_once, I couldn’t, so the once control took any of 3 states (start, initialising, finished). But then I couldn’t change the kernel. Unusual situation).pthread_key_tis like an index for accessing thread-local storage. You can think of each thread as having a map from keys to values. When you add a new entry to TLS,pthread_key_createchooses a key for it and writes that key into the location you specify. You then use that key from any thread, whenever you want to set or retrieve the value of that TLS item for the current thread. The reason TLS gives you a key instead of letting you choose one, is so that unrelated libraries can use TLS, without having to co-operate to avoid both using the same value and trashing each others’ TLS data. The pthread library might for example keep a global counter, and assign key 0 for the first timepthread_key_createis called, 1 for the second, and so on.