Some concepts of threading

Source: Internet
Author: User
Tags terminates

A thread is the smallest unit that the operating system can perform operations on, and is included in the process. A typical unix/linux process can be seen as having only one control thread.

The thread contains the information necessary to represent the in-Process execution environment, including the thread ID of the thread identified in the process, a set of register values, stacks, scheduling priorities and policies, signal-masking words, errno variables, and thread-private data (no separate heap, shared heap). All information within the process is shared with the threads within the process, including executable program text, program global memory and heap memory, stack, and file descriptors.


Thread identity

Like the process ID, each thread also has a thread ID. The process ID is unique across the system, but the thread ID is only valid within the process to which it belongs. The thread ID is represented by the pthread_t data type and can be implemented with a data structure representing the pthread_t data type, so it cannot be processed as an integer in the portable operating system. So two thread ID comparisons must be done with a function

#include <pthread.h>

int pthread_equal (pthread_t tid1, pthread_t Tid2);

Get your own ID can be used

#incude <pthread.h>

pthread_t pthread_self (void);


Thread creation

When you create a line enters upgradeable, you can assume that there is only one master thread in the process. Create threads can use the

#include <pthread.h>

int pthread_create (pthread_t *restrict TIDP,

Const pthread_attr_t *restrict attr.

void * (*START_RTN) (void *), void *restrict arg);

When thread creation returns successfully, the memory unit that TIDP points to is set to the thread ID of the newly created thread. The attr parameter is used to customize various thread properties.

The newly created thread runs from the START_RTN function address, which is followed by an untyped pointer parameter arg, which, if multiple arguments are to be passed, is made into a struct and then passed in to the struct body.

After a thread is created, there is no guarantee which thread will run first: whether it is a newly created or called Thread. The newly created thread can access the address space of the process, inheriting the floating-point environment of the calling thread and the signal mask word, but the thread's pending signal set is cleared.

Pthread returns an error code if it fails, and does not set errno like any other POSIX function. Each thread provides a copy of errno, just to be compatible with existing functions that use errno.

Can be tested by the following code, the function is the print thread ID

#include <pthread.h>pthread_t ntid;voidprintids (const char *s) {pid_t pid;pthread_t tid;pid=getpid (); tid= Pthread_self ();p rintf ("%s pid%u tid%u (0x%x) \ n", s, (unsigned int) PID, (unsigned int) tid, (unsigned int) tid);} Void*thr_fn (void *arg) {printids ("New Thread:"); return ((void*) 0);} int main (void) {int err;err=pthread_create (&ntid,null,thr_fn,null); if (err!=0) printf ("Can ' t create thread:%s\n", Strerror (Err));p rintids ("Main thread:"); sleep (1); exit (0);}

running the results on Fedora is:
main thread:pid 3922 tid 3078109440 (0xb7783900)
New Thread:pid 3922 tid 3078105920 (0XB7782B40)

Sleep (1) is designed to prevent the main thread from ending. Get the thread ID through pthread_self because the function may have run before Pthread_create returns.


Thread termination

Any one thread in a process calls exit,_exit,_exit the entire process terminates. If the signal default action is to terminate the process, sending the signal to the thread also terminates the process.

Terminating a single thread can be done in the following ways:

1, the thread is only returned from the startup routine, the return value is the thread exit code.

2. The thread is canceled by another thread in the same process.

3. Call Pthread_exit

#include <pthread.h>

void Pthread_exit (void *rval_ptr)

Where Rval_ptr is an untyped pointer, it is similar to a parameter passed to the start routine. Other processes in the same process can call the Pthread_join function to get this pointer.

#include <pthread.h>

void Pthread_join (pthread_t thread, void **rval_prt);

One thing to note is that the thread exits the value of the state and can no longer be on the thread's stack. If on the stack, when the thread exits, the stack space is freed.

Threads can cancel other threads in the same process

#include <pthread.h>

int Pthread_cancel (pthread_t tid)

A thread can register cleanup functions called at exit, like Atexit of a process, handlers are recorded in the stack, so the call order is reversed from the registration order

#inlcude <pthread.h>

void Pthread_cleanup_push (void (*RTN) (void *), void *arg);

void Pthread_cleanup_pop (int execute);

Write the code to test some of the above functions:

#include <pthread.h>void cleanup (void *arg) {printf ("cleanup:%s\n", (char *) arg);} void* thr_fn1 (void *arg) {printf ("Thread 1 start\n");p Thread_cleanup_push (cleanup, "Thread 1 First handler");p Thread_ Cleanup_push (Cleanup, "Thread 1 Second handler");p rintf ("Thread 1 Push complete\n"), if (ARG) pthread_exit ((void*) 1); Pthread_cleanup_pop (0);p thread_cleanup_pop (0);p thread_exit ((void*) 1);} void* thr_fn2 (void *arg) {printf ("Thread 2 start\n");p Thread_cleanup_push (cleanup, "Thread 2 first handler");p Thread_ Cleanup_push (Cleanup, "Thread 2 second handler");p rintf ("Thread 2 push complete\n"); if (ARG) return (void*) 2;pthread_ Cleanup_pop (0);p thread_cleanup_pop (0); return (void*) 2;} int main (void) {pthread_t tid1, tid2;void *tret;pthread_create (&AMP;TID1,NULL,THR_FN1, (void *) 1);//Create Thread 1pthread_ Create (&AMP;TID2,NULL,THR_FN2, (void *) 1);//creates thread 2//gets thread exit status Pthread_join (TID1, &tret);//blocks until thread 1 exits printf (" Thread 1 exit Code%d\n ", (int) tret);//directly convert the pointer to Intpthread_join (TID2, &tret);//block until thread 2 exits printf (" Thread 2 ExiT code%d\n ", (int) tret); exit (0);} 

Running the results on Fedora is:

Thread 2 Start
Thread 2 Push complete
Thread 1 start
Thread 1 Push complete
Cleanup:thread 1 Second Handler
Cleanup:thread 1 First Handler
Thread 1 exit code 1
Thread 2 exit code 2

Some concepts of threading

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.