[Linux] Process (eight)---threading concepts

Source: Internet
Author: User

Thread

Concept:
The thread itself basically does not own the system resources, only has a point in the operation of the necessary resources (such as program counters, a set of registers and stacks),
All the information about the process is shared with all threads of the process, including the program text, the program's full memory, heap, stack, and file descriptor.

Thread ID:
The process ID is unique across the system and is represented by the pid_t data type,
The thread ID is valid only in the process environment to which it belongs, represented by the pthread_t data type, with pthread_t pthread_self (void), to obtain its own thread ID.

1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <pthread.h> 4  5 int main () {6     pthread_t th read_id; 7  8     thread_id=pthread_self ();//returns the thread ID of the calling thread 9     printf ("Thread ID:%lu.\n", thread_id);     Pthread_equal (Thread_id,pthread_self ())) {//    if (thread_id==0) {         printf ("equal!\n"); +     } else {15         printf ("Not equal!\n");     +     return 0;18}


Creation of Threads:
Use the Pthread_creat () function: Return value: Success-0, failure-return error number, you can get error message with strerror (errno) function

#include <pthread.h>   int pthread_create (pthread_t *__restrict __newthread,//newly created thread ID                  __const pthread_ attr_t *__restrict __attr,//thread attribute                  void * (*__start_routine) (void *),//The newly created thread starts from Start_routine to execute                  void *__ Restrict __arg)//Parameters of the execution function  


Termination of the thread:
The thread returns from the execution function, and the return value is the thread's exit code
Thread is canceled by another thread of the same process
Call the Pthread_exit () function to exit. This is not called exit, because the thread calls the Exit function, which causes the process of the thread to exit.
thread creation, thread termination instance:

#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <string.h> #include < stdlib.h>pthread_mutex_t mylock=pthread_mutex_initializer;int num = 0;void *add (void *arg) {int i = 0, tmp;for (;i< 10;i++) {pthread_mutex_lock (&mylock); tmp=num+1;num=tmp;printf ("Add result is:%d\n", num);p Thread_mutex_unlock ( &mylock);} Return ((void*) 0);} void *sub (void *arg) {int i=0,tmp;for (; i<10;i++) {pthread_mutex_lock (&mylock); tmp=num-1;num=tmp;printf ("Sub Result is:%d\n ", num);p thread_mutex_unlock (&mylock);} Return ((void*) 0);} int main (int argc,char **argv) {pthread_t tid1,tid2;int err;void *tret;err=pthread_create (&tid1,null,add,null); (Err! = 0) {printf ("Pthread_creat Error:%s\n", strerror (Err)); exit (-1);} Err=pthread_create (&tid2,null,sub,null); if (err! = 0) {printf ("Pthread_creat Error:%s\n", strerror (Err)); Exit (-1 );} Err=pthread_join (Tid1,&tret); if (err! = 0) {printf ("Can not join with Thread1:%s\n", strerror (Err));} printf ("Thread 1 exit CodE\n "); Err=pthread_join (Tid2,&tret);p rintf (" Thread 2 exit code \ n "); return 0;} 


The compile time needs to add-lpthread,

2, Thread synchronization:

Click to open link

(i) Mutex amount:
Two ways to initialize, the first: the assignment is a constant Pthread_mutex_initializer, and the second, when the mutex is dynamically allocated, is initialized with the Pthread_mutex_init function, using the Pthread_mutex_ The Destroy function is destroyed.

#include <pthread.h>   int pthread_mutex_init (pthread_mutex_t *__mutex,                     __const pthread_mutexattr_t *__ MUTEXATTR);  int Pthread_mutex_destroy (pthread_mutex_t *__mutex);  #include <pthread.h>int pthread_mutex_init (pthread_mutex_t *__mutex,       __const pthread_mutexattr_t *__ MUTEXATTR); int Pthread_mutex_destroy (pthread_mutex_t *__mutex); return value: Success-0, failure-error number plus unlock lock call Pthread_mutex_lock, Unlock call Pthread_mutex_unlock. [CPP] View plaincopyprint? #include <pthread.h>   int pthread_mutex_lock (pthread_mutex_t *__mutex);  int Pthread_mutex_unlock (pthread_mutex_t *__mutex);


The use of mutexes should avoid deadlocks, such as a thread attempting to lock the same mutex two times, itself into a deadlock state, another situation is a program
One thread consumes a mutex but tries to get a second mutex, but another thread has already occupied the second mutex but tries to get the first mutex.
You can use the Pthread_mutex_trylock () function to prevent deadlocks
Specifically, the Trylock function, this function is a non-blocking invocation mode, that is, if the mutex is not locked, the Trylock function will lock the mutex and gain access to the shared resources;
If the mutex is locked, the Trylock function will not block the wait and return ebusy directly, indicating that the shared resource is in a busy state

(ii) read/write lock

#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include &  lt;string.h> #define DEBUG 1 int num=0;  pthread_mutex_t Mylock=pthread_mutex_initializer;  pthread_cond_t Qready=pthread_cond_initializer;       void * Thread_func (void *arg) {int i= (int) arg;      int ret;      Sleep (5-i);//thread sleeps, then first generated thread, finally wakes up Pthread_mutex_lock (&mylock);//The mutex must be acquired before Pthread_cond_wait is called while (I!=num)  {#ifdef DEBUG printf ("Thread%d waiting\n", i); #endif ret=pthread_cond_wait (&qready,&mylock);//The function puts the thread into the list of threads waiting for the condition, and then unlocks the mutex, two of which are atomic operations.           And when the pthread_cond_wait returns, the mutex is locked again.  if (ret==0) {#ifdef DEBUG printf ("Thread%d wait success\n", i);  #endif}else {#ifdef DEBUG printf ("Thread%d wait failed:%s\n", I,strerror (ret));      #endif}} printf ("Thread%d is running \ n", i);      num++; Pthread_mutex_unlock (&mylOck);//Unlock pthread_cond_broadcast (&qready);//Wake Up all threads waiting for the condition return (void *) 0;      } int main (int argc, char** argv) {int i=0,err;      pthread_t Tid[4];      void *tret;          for (; i<4;i++) {Err=pthread_create (&tid[i],null,thread_func, (void *) i);              if (err!=0) {printf ("Thread_create error:%s\n", strerror (err));          Exit (-1);          }} for (i = 0; i < 4; i++) {err = Pthread_join (Tid[i], &tret);              if (err! = 0) {printf ("Can not join with thread%d:%s\n", I,strerror (err));          Exit (-1);  }} return 0; }



(iii) Condition variables
To prevent competition, the use of condition variables is always combined with a mutex.

[Linux] Process (eight)---threading concepts

Related Article

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.