Linux multithreaded programming

Source: Internet
Author: User

Linux multithreaded programming


A thread is a complete sequence of execution that completes a separate task in a program, that is, an entity that can be dispatched. Depending on the identity of the running environment, threads can be divided into kernel threads and user threads. Kernel threads, on some systems called LWP (Light Weight Process, lightweight threads), run in kernel space, are dispatched by the kernel, and user threads run in user space and are dispatched by line libraries. When a kernel thread of a process obtains the right to use the CPU, it loads and runs a user thread. It can be seen that the kernel thread is equivalent to the ' container ' that the user thread is running, a process that has m kernel threads and n user threads, where m<=n, and the ratio of M and N is fixed in all processes of a system.

The different threads in the process are not as independent as the different processes, and all the lines threads exactly the same address space, which means they share the same global variables. In addition to the shared address space, all threads share the same open file set, child processes, and related signals, each with its own stack.

In the case of multithreading, the process typically starts with the current single thread, which has the ability to create a new thread by invoking a library function (such as pthread_create), and the parameters of the Thread_create function specify the name of the function to run.



Thread control functions

Thread Creation pthread_create

#include <pthread.h>int pthread_create (pthread_t * TIDP, const pthread_attr_t *attr, void * (*START_RTN) (void *), VO ID *arg); return: Successful return 0, error return number
When the Pthread_create function returns success, the memory pointed to by TIDP is set to the thread ID of the newly created thread, whose type pthread_t is defined as

#include <bits/pthreadtypes.h>typedef unsigned long int pthread_t;

The attr parameter is used to customize a variety of different thread properties, which are null when the default thread property is represented. The newly created thread runs from the address of the START_RTN function, which has only one parameter arg with an untyped pointer, and if more than one parameter is required to pass to the START_RTN function, you can put the parameter into a struct and then pass the address of the struct as a parameter to ARG.

When a thread is created, it does not guarantee which thread will run first: whether it is a newly created thread or a calling thread. The newly created thread can access the address space of the calling process and inherit the calling thread's floating-point environment and the signal-mask word, but the thread's pending signal set is cleared.


Thread Termination Pthread_exit

#include <pthread.h>void pthread_exit (void *rval_ptr);

It is best to call this function at the end of the thread to ensure a safe, clean exit. The Pthread_exit function passes the exit information to the collector of the calling thread through the Rval_ptr parameter, and other threads in the process can call the Pthread_join function to access the pointer. Pthread_exit will not return to the caller after execution, and will never fail.

A thread can exit in the following three ways, stopping its control flow without terminating the entire process:

The thread just exits from the boot process, and the return value is the thread's exit code

L threads can be canceled by other threads in the same process

L Thread Call Pthread_exit


Pthread_join

#include <pthread.h>int pthread_join (pthread_t thread, void **rval_ptr); return: Successful return 0, error code returned
The thread is the target thread identifier, and rval_ptr points to the exit information when the target thread returns, and the function blocks until the thread that is recycled ends. The possible error codes are:


Cancel Thread Pthread_cancel

#include <pthread.h>int pthread_cancel (pthread_t thread); return: Successful return 0, error code returned

By default, the Pthread_cancel function causes threads that have thread identity to behave as if the Pthread_exit function with the parameter pthread_cancel is called, but the target thread that receives the cancellation request can decide whether to allow cancellation and how to cancel , which are controlled by two functions, respectively.

#include <pthread.h>int pthread_setcancelstate (int state, int *oldstate), int pthread_setcanceltype (int type, int *oldstate);

Note that Pthread_cancel does not wait for the thread to end, it simply requests.


Simple example of creating a thread :

#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define ERR_SYS (msg) do {perror (msg); exit (-1);  The while (0) #define ERR_EXIT (msg) does {fprintf (stderr, msg); exit ( -1);} while (0) void *thread_func (void *arg) {printf ("Hello World!\n "); Sleep (1);p thread_exit (" Hdu ");} int main (void) {pthread_t tid;char* p = null;pthread_create (&tid, NULL, THREAD_FUNC, NULL);p Thread_join (tid, (void * * ) &p);p rintf ("message:%s\n", p); return 0;}

Reference:

1, "Linux High Performance Server programming," the 14th Chapter multithreaded programming


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Linux multithreaded programming

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.