Linux system Programming-multithreading for multitasking

Source: Internet
Author: User

Overview

each process has its own data segment, code snippet, and stack segment, which causes the process to create, switch, and undo operations with a large overhead. to reduce system overhead, threads are evolved from the process. The process must contain at least one thread in order for the process to do some work. a thread exists in the process and shares the resources of the process. For more details, see " process and thread differences and linkages ".


Just as each process has a process number, each thread also has a thread number. The process number is unique across the system, but the thread number is different, and the thread number is only valid in the process environment to which it belongs. The process number is represented by the pid_t data type and is a non-negative integer. The thread number is represented by the pthread_t data type, and Linux uses an unsigned long integer representation. Some systems, when implemented pthread_t, are represented by a struct, so the portable operating system implementation cannot treat it as an integer.


common functions for threads

1) Get the thread number

Required header file:

#include <pthread.h>


pthread_t pthread_self (void);

Function:

Gets the thread number.

Parameters:

No

return value:

The thread ID of the calling thread.


2) Comparison of thread numbers

Required header file:

#include <pthread.h>


int pthread_equal (pthread_t t1, pthread_t T2);

Function:

Determines whether the thread number T1 and T2 are equal. To facilitate porting, use functions to compare thread IDs as much as possible.

Parameters:

t1,t2: The thread number to be judged.

return value:

Equality: not 0

Unequal: 0


Example code:

#include <stdio.h> #include <stdlib.h> #include <pthread.h>int main (int argc, char *argv[]) {pthread_t thread_id;thread_id = Pthread_self (); Returns the thread idprintf of the calling thread ("thread ID =%lu \ n", thread_id), if (0! = pthread_equal (thread_id, Pthread_self ())) {printf ("equal!\ n ");} else{printf ("not equal!\n");} return 0;}

thread function of the program in the Pthread library, so link to add parameter-lpthread.


The results of the operation are as follows:



3) Creation of threads

Required header file:

#include <pthread.h>


int Pthread_create (pthread_t *thread,

const pthread_attr_t *attr,

void * (*start_routine) (void *),

void *arg);

Function:

Creates a thread.

Parameters:

Thread: Threads identifier address.

attr: Thread attribute struct body address, usually set to NULL.

start_routine: The entry address of the thread function.

arg: The argument passed to the thread function.

return value:

Success: 0

Failure: not 0


The thread created by Pthread_create () runs from the specified callback function, and the thread exits when the function finishes running. Thread-dependent processes exist, sharing the resources of the process, and if the process that created the thread ends, the thread ends.


Example one:

#include <stdio.h> #include <unistd.h> #include <pthread.h>int var  = 8;void *thread_1 (void *arg) { while (1) {printf ("This is my new thread1:var++\n"); Var++;sleep (1);} return NULL;} void *thread_2 (void * arg) {while (1) {printf ("This is my new Thread2:var =%d\n", var); sleep (1);} return NULL;} int main (int argc, char *argv[]) {pthread_t tid1,tid2;//Create two threads pthread_create (&TID1, NULL, thread_1, NULL);  Pthread_create (&tid2, NULL, thread_2, NULL), while (1) {printf ("the main Thread:var =%d\n", var), and Sleep (1);} return 0;}

The results of the operation are as follows:



Example two:

#include <stdio.h> #include <unistd.h> #include <pthread.h>//callback function void *thread_fun (void * arg) {sleep ( 1) int num = * ((int *) arg);p rintf ("int the new thread:num =%d\n", num); return NULL;} int main (int argc, char *argv[]) {pthread_t Tid;int test = 100;//Create thread, pass &test to callback function Thread_fun () pthread_create (& Tid, NULL, Thread_fun, (void *) &test);  while (1); return 0;}

The results of the operation are as follows:



4) Recycle Thread resources

Required header file:

#include <pthread.h>


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

Function:

Wait for the thread to end (this function will block) and reclaim the thread resources, similar to the process's wait () function. If the thread has ended, the function returns immediately.

Parameters:

Thread: The number of threads that are waiting.
retval: The address of the pointer used to store the thread exit status.

return value:

Success: 0

Failure: not 0


The sample code is as follows:

#include <stdio.h> #include <unistd.h> #include <pthread.h>void *thead (void *arg) {static int num = 123; Static variable printf ("After 2 seceonds, thread would return\n"), Sleep (2), return #}int main (int argc, char *argv[]) {pthread_t tid;i NT ret = 0;void *value = null;//Create thread ret = pthread_create (&tid, NULL, THEAD, NULL); if (ret! = 0) {//Create failed perror ("Pthread _create ");} The thread that waits for the thread number to be tid, if the thread ends up reclaiming its resources//&value The return value of the Save thread exit Pthread_join (Tid, &value); printf ("value =%d\n", * ((int *) value)); return 0;}

The results of the operation are as follows:



After creating a thread, it should reclaim its resources, but using the Pthread_join () function will block the caller, and Linux also provides a non-blocking function Pthread_detach () to reclaim the thread's resources.


Required header file:

#include <pthread.h>


int Pthread_detach (pthread_t thread);

Function:

Separates the calling thread from the current process, which does not mean that the thread is not dependent on the current process, and that the thread separation is done by the system to automate the recycling of the thread resources, that is, when the disconnected thread ends, the system automatically reclaims its resources. Therefore, this function does not block.

Parameters:

Thread: Number of threads.

return value:

Success: 0

Failure: not 0


Note that when you call Pthread_detach () and then call Pthread_join (), Pthread_join () returns immediately and the call fails.


The sample code is as follows:

#include <stdio.h> #include <unistd.h> #include <pthread.h>void *thead (void *arg) {int i;for (i=0; i <5; i++) {printf ("I am runing\n"); sleep (1);} return NULL;} int main (int argc, char *argv[]) {int ret  = 0;pthread_t Tid;ret = pthread_create (&tid, NULL, THEAD, NULL); if (ret!=0 {perror ("pthread_create");} Pthread_detach (TID); Thread detach, do not block//return immediately, call failed int flag = Pthread_join (tid, NULL), if (flag! = 0) {printf ("Join not working\n");} printf ("After join\n"); Sleep (3);p rintf ("I am leaving\n"); return 0;}

The results of the operation are as follows:



5) Thread exit

In the process we can call the exit () function or the _exit () function to end the process, and in one thread we can stop its control flow by Pthread_exit () without terminating the entire process.


Required header file:

#include <pthread.h>


void Pthread_exit (void *retval);

Function:

Exits the calling thread. More than one thread in a process is the data segment that shares the process, so the resources that are typically consumed after the thread exits are not freed.

Parameters:

retval: A pointer to the store thread exit state.

return value:

No


The sample code is as follows:

#include <stdio.h> #include <unistd.h> #include <pthread.h>void *thread (void *arg) {static int num = 123 ; static variable int i = 0;while (1) {printf ("I am runing\n"), Sleep (1), i++;if (i==3) {pthread_exit ((void *) &num);//Return #}} return NULL;}  int main (int argc, char *argv[]) {int ret  = 0;pthread_t tid;void *value  = Null;ret = Pthread_create (&tid, NULL, Thread, NULL);  if (ret!=0) {perror ("pthread_create");} Pthread_join (Tid, &value);p rintf ("value =%d\n", * (int *) value); return 0;}

The results of the operation are as follows:



Please click this link to download the sample code for this tutorial.

Linux system Programming-multithreading for multitasking

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.