11.4 Thread Creation

Source: Internet
Author: User


Each process in the traditional UNIX programming model supports only one thread control, conceptually, the same as a threading model where each thread is composed of just one thread. After using Pthreads, when a program runs, the system will also start a single-threaded control process, when the program is running, its behavior is not significantly different from the traditional process, unless it creates multithreading control, other threads can be created by calling function Pthread_create.

  
 
  1. #include <pthread.h>
  2. int pthread_create(pthread_t *restrict tidp,
  3. const pthread_attr_t *restrict attr,
  4. void *(*start_rtn)(void *), void *restrict arg);
  5. Returns: 0 if OK, error number on failure.

The memory address that the TIDP pointer points to will be set to the thread ID of the newly created thread after the function pthread_create successfully returns, the parameter attr is used to customize the thread properties, we will tell the thread properties in 12.3, and now we just pass NULL to it. To create a thread that has a default property.
The newly created thread will run from address Start_rtn with only one parameter, ARG, which is an unsigned pointer. If you need to pass an extra parameter, you need to store these parameters in a struct and pass the structure's address to Arg.
When a new thread is created, which thread runs first without any guarantee, the newly created thread has access to the process address space and inherits the calling thread's floating-point environment and the signal mask, but the signaled signal will be cleared.
Note that the Pthread function only returns an error code when an error occurs, and they do not set errno like other POSIX functions. Each thread has a errno copy to ensure compatibility with the errno function. With Threads,it are cleaner to return the error code from the Function,thereby restriciting the scope of the error to the F Unction that caused it, instead of relying in some global state, which is changed as a side of the function.

Example

Although there is no way to have a portable print process ID, we can write a small program to see how a thread is working. The program in Figure 11.2 creates a thread and prints the thread ID and process ID of the newly created thread and the original thread.

  
 
  1. #include "apue.h"
  2. #include <pthread.h>
  3. pthread_t ntid;
  4. void printids(const char *s)
  5. {
  6. pid_t pid;
  7. pthread_t tid;
  8. pid = getpid();
  9. tid = pthread_self();
  10. printf("%s pid %lu tid %lu (0x%lx)\n", s, (unsigned long)pid,
  11. (unsigned long)tid, (unsigned long)tid);
  12. }
  13. void *thr_fn(void *arg)
  14. {
  15. printids("new thread: ");
  16. return ((void *)0);
  17. }
  18. int main(void)
  19. {
  20. int err;
  21. err = pthread_create(&ntid, NULL, thr_fn, NULL);
  22. if(err != 0)
  23. {
  24. err_exit(err, "cann‘t create thread");
  25. }
  26. printids("main thread: ");
  27. sleep(1);
  28. exit(0);
  29. }

Figure 11.2 Print Thread ID

The program has two special properties that are necessary to handle race conditions between the main thread and the new thread. We will learn a better way to deal with race conditions later in this chapter.

    1. The main thread needs to sleep, and if the main thread sleeps, the main thread ends the run exit, so it is possible that the entire process has terminated before the new process starts running, which is related to the threading implementation of the operating system and the scheduling algorithm.
    2. The new thread obtains its own thread ID by calling the function Pthread_self function, rather than by reading from shared memory or by the arguments of its thread run function, as we mentioned above, Pthread_create will return the thread ID of the newly created thread to the first parameter (TIDP), in our case, the main thread will store the child thread ID into Ntid, but the new threads are not guaranteed to be safe to use, because if the new thread starts running before the thread, and the master thread has not returned from the Pthread_create function, The new thread will see an uninitialized ntid entity instead of the correct thread ID.

The effect is as follows:

  
 
  1. [email protected]:~/UnixProgram/Chapter11$ ./11_2Exe
  2. main thread: pid 2340 tid 3077592768 (0xb77056c0)
  3. new thread: pid 2340 tid 3077589872 (0xb7704b70)
  4. [email protected]:~/UnixProgram/Chapter11$

You can see that the result is the same as expected, with two threads having the same process ID, but with different thread IDs.



From for notes (Wiz)

11.4 Thread Creation

Related Article

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.