linux--thread basic concepts and thread separation __linux

Source: Internet
Author: User
Tags terminates

Thread:

A What is a thread (TCB).

Threads are run within the process address space, emphasizing resource sharing (multiple threads share an address space). Linux is a process to simulate the thread, there is no real thread. A process is the basic unit of allocating resources, and a thread is the basic unit of dispatch.


Two Threads can be shared and exclusive.

Shared by:

1. File Description Chart

2. How each signal is processed (sig_ign, SIG_DFL, or custom signal processing function)

3. Current working directory

4. User ID and Group ID

Exclusive of:

1. Thread ID

2. Context, including the values of various registers, program counters and pointers.

3. Stack space

4. Signal Shielding Word

5. Scheduling priority

Three Thread operations (compliance with POSIX standards)

Thread creation:

int Pthread_create (pthread_t *thread, constpthread_attr_t *attr,void * (*start_routine) (void *), void *arg);

Return value: Successfully returned 0, failure returned error code

pthread_t *thread: Thread ID, only valid in user area, created and attached.

pthread_attr_t *attr: Typically null, set thread properties.

void * (*start_routine) (void *): A function pointer that executes the code in this function after the call.

void *arg: A parameter for the third parameter. is generally null.

Thread Termination:

void Pthread_exit (void *retval);

Parameter: Reval is a void* type, as is the use of the thread function return value, and other threads can invoke Pthread_join to obtain this pointer. Pthread_exit or return returns a pointer to a cell that must be global or allocated with malloc and cannot be allocated on a stack of thread functions, because the thread has exited when the other thread gets the return pointer.

Thread Cancellation:

int Pthread_cancel (pthread_t thread);

Return value: Successful return of 0, failure return error code.

Thread Wait:

int Pthread_join (pthread_t thread,void **retval);

The thread that calls the function suspends the wait until the thread with ID thread terminates. Thread threads with different. Methods terminate, the termination status obtained by Pthread_join is different, summarized as follows:

1. If the thread thread returns via return, the value_ptr points to a cell that holds the return value of the thread function.

2. If the thread thread is called by another thread to pthread_cancel the exception, the value_ptr points to a constant pthread_canceled.

3. If the thread thread is called by itself Pthread_exit terminated. Value_ptr points to a cell that holds the parameters passed to Pthread_exit. If you are not interested in the end state of the thread threads, you can pass NULL to the VALUE_PTR parameter.

The following verifies the state of the thread when it exits

void * THREAD_RUN1 (void *arg) {printf ("Thread_run1:tid:%lu pid:%d \ n", Pthread_self (), Getpid ());
Return ((void*) 1);
       } void * Thread_run2 (void *arg) {printf ("Thread_run2:tid:%lu pid:%d\n", Pthread_self (), Getpid ());
       Pthread_exit ((void*) 2);
Return ((void*) 1); } void * Thread_run3 (void *arg) {while (1) {printf ("Thread_run3:tid:%lu pid:%d \ n", Pthre
                Ad_self (), Getpid ());
       Sleep (1);
return NULL;
       int main () {pthread_t id;
       void *temp;
       Check his ID and return value pthread_create (&id,null,thread_run1,null) at normal exit;
       Pthread_join (id,&temp);
 
       printf ("Thread_run1 return:id%u return code%d\n", ID, (int) temp);
       Pthread_create (&id,null,thread_run2,null) when the intermediate call thread terminates;
       Pthread_join (id,&temp);
 
       printf ("Thread_run2 return:id%u return code%d\n", ID, (int) temp); When the thread is dead-loop when the thread is canceled with a function pthread_create (&id,null,thread_run3, NULL);
       Sleep (1);
       Pthread_cancel (ID);
       Pthread_join (id,&temp);
 
       printf ("Thread_run3 return:id%u return code%d\n", ID, (int) temp);
       printf ("The main tid is%u pid%d\n", Pthread_self (), Getpid ());
return 0; }


Run Result:

threading and Separation and binding:

At any point in time, threads are either associative (joinable) or detached (detached). A thread that can be combined can be retrieved by other threads and killed by its resources. Its memory resources, such as stacks, are not released until they are reclaimed by another thread. Conversely, a detached thread cannot be recycled or killed by another thread, and its memory resources are automatically released by the system when it terminates.

The created thread default property is associative, so it has to wait for it to produce a zombie-like process.

If the thread is separable, no join is required and all resources are automatically freed when the thread is run.

Verify that the detached thread can wait for join

void *thread_run (void * arg)
{
        Pthread_detach (pthread_self ());
        printf ("%s\n", (char*) arg);
        return NULL;
}
 
int main ()
{
        pthread_t id;
        int temp =pthread_create (&id,null,thread_run, "Thread1 run\n");
        if (temp!= 0)
        {
                printf ("Create errorcode:%s\n", strerror (temp));
                return-1;
        }
        A detached thread cannot be killed or recycled by another process so the last recycle failed
        int ret = 0;
        Sleep (2);
        if (0 = = Pthread_join (id,null))
        {
                printf ("Thread waitsuccess\n");
                ret = 0;
        }
        else {
                printf ("Thread waitfailed\n");
                ret = 1;
        }
                return ret;
}

synchronization and mutex of threads (equivalent to a lock, two-yuan semaphore):

Initialization: pthread_mutex_t Mutex_lock = Pthread_mutex_initializer

Lock: Pthread_mutex_t_lock (&mutex_lock);

Unlock: Pthread_mutex_t_unlock (&mutex_lock);

If there is no lock and locks

Adding the final result when executing four threads at the same time does not necessarily mean that we want to get a value because there is a data inconsistency problem.

When we lock the locks, the values will be the same.

pthread_mutex_t mx= pthread_mutex_initializer; static int g_count= 0; void *read_write_mem (void * _val)
        {int val = 0;
        int i = 0;
                for (; i<5000;++i) {pthread_mutex_lock (&MX);
                val = g_count;
                printf ("Pthread idis:%x,count is:%d \ n", Pthread_self (), g_count);
                G_count = val+1;
        Pthread_mutex_unlock (&MX);
return NULL;
        int main () {pthread_t tid1;
        pthread_t Tid2;
        pthread_t tid3;
        pthread_t Tid4;
        Pthread_create (&tid1,null,read_write_mem,null);
	Pthread_create (&tid2,null,read_write_mem,null);
        Pthread_create (&tid3,null,read_write_mem,null);p thread_create (&tid4,null,read_write_mem,null);
        Pthread_join (Tid1,null);
        Pthread_join (Tid2,null);
        Pthread_join (Tid3,null);
        Pthread_join (Tid4,null);
        printf ("Count Val is%d\n", G_count);
return 0; }

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.