POSIX multithreading-Thread basic concepts

Source: Internet
Author: User
Tags file copy mutex posix terminates

http://blog.csdn.net/livelylittlefish/article/details/7957007

Awa
Links: http://blog.csdn.net/livelylittlefish/article/details/7957007

(The whole year is not updated, send a few previous reading notes.) )

Content

1. thread creation and use

    • Creating Threads
    • Initial thread
    • Thread separation

2. Thread life cycle

    • Ready state
    • Be blocked
    • Thread termination
    • Thread Recycling

1. thread creation and use

Creating Threads

    • Create a thread with the pthread_create () function;
      • Pass the thread function address and thread function parameters to the function;
      • The thread function has only one void* parameter;
      • The function returns the thread ID of the pthread_t type ;
    • Call this function to create a thread, and then call the pthread_join () function to wait for the thread to end;
    • There is no synchronization relationship between the current thread returning from the function pthread_create () and the new thread being scheduled to execute;
      • The new thread may have run before the current thread returns a value from Pthread_create ();
      • Or, before the current thread returns from Pthread_create () , the new thread may have finished running;

Pthread_join ()

    • Blocks its caller until the specified thread terminates, and optionally saves the thread's return value;
    • When the pthread_join () call returns, the connected thread is separated (detached), andthe thread is no longer connected;
    • If the connection (joining) thread does not care about the return value, or if it knows that the thread being connected (joined) does not return any value at all, it can be pthread_join () &retval parameter is passed NULL, at which point the returned value of the connected thread is ignored;

How to use can refer to pthread_create (),pthread_join () manual;

Initial thread

    • C When the program runs, first run the main () function, themain () function is called the initial thread or the main process;
    • The initial thread can call pthread_self () to get its ID, or it can call Pthread_exit () to terminate itself;
      • returning from Main () will cause the process to terminate and will also terminate the thread used in the process;
      • Call Pthread_exit () in main () so that the process must wait for all threads to end before terminating;
    • If the initial thread stores its ID in a space that other threads can access, other threads can wait for the initial thread to terminate or detach the initial thread;

Thread separation

    • Separating a running thread does not have any effect on the thread, but merely notifies the system that its owning resource can be reclaimed when the thread ends;
    • Detaching a thread means notifying the system that the thread is no longer needed, allowing the system to recycle the resources allocated to it;
    • A thread that is not separated will retain its virtual memory, including the stack and other system resources, when it terminates.

2. Thread life cycle

At any point in time, the thread is in one of the four basic states of the following table.

State

Description

Ready

The thread is able to run, but waits for the available processor;

  • Probably just started.
  • Or just recovering from a blockage.
  • Or be preempted by another thread

Run running

threads are running; In multiprocessor systems, multiple threads may be running;

Blocking blocked

A thread cannot run because it waits for other conditions outside the processor, such as changing the condition variable, locking the mutex, or the end of the IO operation;

Terminate terminated

is not separated, is not connected, once the thread is separated or connected, it can be recycled;

  • The thread returns from the Start function
  • or call pthread_exit
  • Or be canceled, terminate yourself and complete all resource cleanup work;

Thread state transitions such as.

Description

    • The thread starts to be in the ready state;
    • When a thread is running, it invokes a specific starting function;
    • It may be preempted by other threads, or blocked by waiting for something external;
    • The final thread completes the work, or returns from the starting function, or invokes the pthread_exit function, which is the terminating state;
    • If the thread has been detached, it is immediately reused, otherwise the thread stays in the terminating state until it is detached or connected;

Ready state

    • When the line Cheng Gang is created;
    • The thread is unblocked again when it can run;
    • When running threads are preempted, such as time slices to;

Be blocked

    • Attempting to lock a mutex that has been locked;
    • Wait for a condition variable;
    • Call singwait wait signal;
    • Perform IO operations that cannot be completed immediately;
    • System operation such as memory page error;

The initial thread (the main () function is threaded ) differs from the normal thread

    • The startup function of the initial thread, main () is called from outside the program, such as the crt0.o file copy initialization process and the main () function, while the normal thread's startup function and its operating parameters are all determined by Pthread The _create () function is passed in when the thread is created and dispatched by the CPU;
    • The parameters of the main () function are argc and argv; the parameters of the normal thread are void* and are passed in by the pthread_create () function;
    • If the normal thread is returned from the startup function, the thread terminates while the other threads are still operational, but when the initial thread returns from main () , the process terminates and all threads in the process are terminated;
      • If you want other threads in the process to continue executing when the initial thread terminates, you will need to call Pthread_exit () instead of the main () in the initial thread tune.
    • In most systems, the initial thread runs on the default process stack, which can grow to a sufficient size, while in some implementations, the stack space of a normal thread is limited;
      • If the thread stack overflows, the program will have a segment error;

Thread sleep Causes

    • is blocked, a resource that is needed is not available;
    • Be preempted, that is, the system assigns the processor to other threads;

A detailed explanation of pthread_join ()

    • Used to wait for the end of a thread;
      • is a thread-blocking function, and the function that invokes it waits until the thread that is waiting ends;
      • For example, the main thread call pthread_join () waits for the threads it creates to run to the end, that is, the main thread calls the function and is blocked;
      • When the function returns, the resources of the waiting thread are recycled;
    • If the new thread is not running at this time, it will enter the running state from the ready state after the main thread is blocked, and when the new thread is finished and returned, the main thread will be unblocked, return to the ready state, or the main thread can be executed immediately when the processor is available, or wait until the created thread terminates and then rerun until the end;

Thread termination

    • Generally, the thread terminates itself by returning from the start function;
    • When calling Pthread_exit () to exit the thread or call Pthread_cancel () to cancel the thread, the thread also enters the terminating state after each cleanup process is invoked;
    • The cleanup process is also registered by Pthread_cleanup_push () and has not been removed by Pthread_cleanup_poo () .

Linux System Zombie Threads

    • If the thread has been detached, it will be recycled, otherwise the thread is in a signaled state and can still be called by other threads to pthread_join () connection;
    • This thread is called a zombie thread, as the process in a Unix system has ended but has not yet been recycled by a wait/waitpid call, even if it is dead but still exists;
    • A zombie thread may retain most or all of its resources at runtime, so the thread should not be in this state for long periods of time, and when creating a thread that does not need to be connected, the thread should be created using the detachstate property to automatically detach it;

Thread Recycling

    • If you use the detachstate property ( that is, set the property to Pthread_create_detach) , or call Pthread_detach () to detach the thread, When the thread ends, it is immediately recycled;
    • If the terminating thread is not detached, it will remain in the terminating state until it is detached ( via Pthread_detach) or connected ( via pthread_join);
    • Once the thread is detached, it can no longer be accessed;
    • Recycling frees all system and process resources that were not released when the thread terminated, including
      • Saves the memory space, stack of the thread return value;
      • Memory space for saving register state;
      • In fact, the above resources can not be accessed when the thread terminates;
    • Once the thread is recycled, the thread ID is invalid and no further connection, cancellation, or any other action can be made;
      • The terminating thread ID may be assigned to a new thread;

NPTL (Native POSIX Threads Library)

This is the modern Pthreads implementation. By comparison with Linuxthreads, NPTL provides closer conformance to therequirements of the POSIX.1 specification and be  Tter performance when creating largenumbers of threads. NPTL is available since glibc 2.3.2, and requires features this is present in Thelinux 2.6 kernel.

Thread-safe functions

A Thread-safe function is one so can be safely (i.e., it'll deliver the same results regardless of Whetherit is) Calle D from Multiplethreads at the same time.

Reference

# Man Pthreads

# Man Pthread_create

# Man Pthread_join

# Man Pthread_exit

# Man Pthread_cancel

POSIX multithreading-Thread basic concepts

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.