Linux multithreading implementation and thread synchronization function analysis

Source: Internet
Author: User
Tags function prototype semaphore

In Linux, the nature of multithreading is still the process, and it differs from the process:

Process: Independent address space, with PCB

Threads: There are also PCBs, but no separate address space (shared)

Features of the thread:

1, the thread is a lightweight process, there is a PCB, the creation of threads using the underlying functions and processes, are clone

2, from the kernel to see the process and threads are the same, have their own different PCB

3, the process can be transformed into a thread

4, in Linux, the thread is the smallest execution unit, and the process is the smallest allocation resource unit

To view the LWP number command for a specified thread:

PS-LF PID

Threading Benefits:

Improve program concurrency

Low Overhead

Data communication for easy sharing

Thread Disadvantage:

Library functions, unstable

debugging, writing difficulties, GDB

Not good for signal support

Thread properties, you can set the separation state at the beginning, specific in the following code is explained!

Thread synchronization, main mutex mutex, read/write lock, condition variable, semaphore

Thread creation function prototype:

int pthread_create (    pthread_t *thread,  //thread ID    const pthread_attr_t *attr,//thread attribute    void * (*start_ routine) (void *),//thread main function    void *arg//main function parameter);

Stick to the basic create threading model:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include < Unistd.h> #include <pthread.h>//function callback void *mythread (void *args) {printf ("Child thread id==[%ld]\n", Pthread_ Self ());} int main () {pthread_t thread;//creates a thread int ret = pthread_create (&thread, NULL, mythread, NULL), if (ret!=0) {printf (" Pthread_create error, [%s]\n], strerror (ret)); return-1;} printf ("Main thread id==[%ld]\n", pthread_self ()); sleep (1);}

Thread properties, separating the code at creation time:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include < unistd.h> #include <pthread.h>void *mythread (void *args) {printf ("Child thread Id==[%ld]\n", pthread_self ());} int main () {pthread_t thread;//thread property pthread_attr_t attr;//Thread Property initialization pthread_attr_init (&attr);//Set thread to detach attribute Pthread_ Attr_setdetachstate (&attr, pthread_create_detached);//create a thread int ret = Pthread_create (&thread, &attr, Mythread, NULL), if (ret!=0) {printf ("Pthread_create error, [%s]\n", Strerror (ret)); return-1;} printf ("Main thread id==[%ld]\n", Pthread_self ()), sleep (1), ret = Pthread_join (thread, NULL), if (ret!=0) {printf (" Pthread_join error, [%s]\n], strerror (ret));} Release Thread Properties Pthread_attr_destroy (&attr); return 0;}

Mutex implementation code:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include < unistd.h> #include <pthread.h> #include <time.h>//define a lock pthread_mutex_t mutex;void *mythread1 (void * args) {while (1) {//Locking Pthread_mutex_lock (&mutex);p thread_mutex_lock (&mutex);p rintf ("Hello"); Sleep (rand ()% 3);p rintf ("world\n");//Unlock Pthread_mutex_unlock (&mutex); Sleep (rand ()%3); Pthread_exit (NULL);} void *mythread2 (void *args) {while (1) {//Locking Pthread_mutex_lock (&mutex);p rintf ("HELLO"); Sleep (rand ()%3);p rintf (" World\n ");//Unlock Pthread_mutex_unlock (&mutex); Sleep (rand ()%3); Pthread_exit (NULL);} int main () {int ret;pthread_t thread1;pthread_t thread2;//random number seed srand (Time (NULL));//Mutex Initialization pthread_mutex_init (& Mutex, null), ret = pthread_create (&thread1, NULL, MYTHREAD1, NULL), if (ret!=0) {printf ("Pthread_create error, [%s]\n ", Strerror (ret)); return-1;} ret = pthread_create (&thread2, NULL, MYTHREAD2, NULL), if (ret!=0) {printf ("Pthread_create error, [%s]\n], strError (ret)); return-1;} Wait for thread to end Pthread_join (thread1, NULL);p thread_join (thread2, NULL);//Release Mutex Pthread_mutex_destroy (&mutex); return 0 ;}

Read-write lock code:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include < unistd.h> #include <pthread.h>int number = 0;//defines a read-write lock pthread_rwlock_t rwlock;void *fun_write (void *args) {int i = * (int *) Args;int n;while (1) {//Add write lock Pthread_rwlock_wrlock (&rwlock); n = number;n++;//sleep (rand ()%3); number = n; printf ("w->[%d]:[%d]\n", I, number);//write Lock Pthread_rwlock_unlock (&rwlock); Sleep (rand ()%3); Pthread_exit (NULL);} void *fun_read (void *args) {int i = * (int *) Args;while (1) {//Read-lock Pthread_rwlock_rdlock (&rwlock);p rintf ("r->[%d]: [%d]\n ", I, number);//Unlock Pthread_rwlock_unlock (&rwlock); Sleep (rand ()%3); Pthread_exit (NULL);} int main () {int i;int ret;int n = 8;int arr[8];p thread_t thread[8];//Read-write lock initialization pthread_rwlock_init (&rwlock, NULL);// Create 3 Write threads for (i=0; i<3; i++) {Arr[i] = I;ret = Pthread_create (&thread[i], NULL, Fun_write, (void *) &arr[i]); if ( ret!=0) {printf ("Pthread_create error, [%s]\n", Strerror (ret)); return-1;}} Create 5 read threads for (i=3; i<n; i++) {Arr[i] = I;ret = Pthread_create (&thread[i], NULL, Fun_read, (void *) &arr[i]), if (ret!=0) {printf ("Pthread_ Create error, [%s]\n], strerror (ret)); return-1;}} for (i=0; i<n; i++) {//Recycle child thread Pthread_join (Thread[i], NULL);} Release read-write lock resource Pthread_rwlock_destroy (&rwlock); return 0;}

Cond condition Variable code:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include < unistd.h> #include <pthread.h>typedef struct node{int data;struct node *next;} node;//Chain Header node pointer nodes *head = null;//Mutex pthread_mutex_t mutex;//condition variable pthread_cond_t cond;//producer thread handler void *producer (void * args) {Node *pnode = null;while (1) {Pnode = (node *) malloc (sizeof (node)), if (pnode==null) {perror ("malloc error\n"), Exit ( 1);} Pnode->data = rand ()%1000;//lock shared resource Pthread_mutex_lock (&mutex);p node->next = head;head=pnode;printf ("P:[ %d]\n ", head->data);//Unlock Pthread_mutex_unlock (&mutex) for shared resources;//Use condition variable to unblock thread to block pthread_cond_signal (&cond) ; Sleep (rand ()%3);}} Consumer threading function void *consumer (void *args) {NODE *pnode = null;while (1) {//lock shared resource pthread_mutex_lock (&mutex); if (head= =null) {//condition does not meet blocking wait head is not empty pthread_cond_wait (&cond, &mutex);} printf ("c:[%d]\n", Head->data);p node = Head;head = head->next;//unlocks the shared resource Pthread_mutex_unlock (&mutex); Pnode);p node = NULL;sleep (rand ()%3);}} int main (int argc, char *argv[]) {int ret;pthread_t thread1;pthread_t thread2;pthread_mutex_t mutex;pthread_cond_t cond ;//Initialize Mutex pthread_mutex_init (&mutex, NULL);//Initialize condition variable pthread_cond_init (&cond, NULL);//create producer thread ret = Pthread_ Create (&thread1, NULL, producer, NULL), if (ret!=0) {printf ("Pthread_create error, [%s]\n", Strerror (ret)); return-1 ;} Create a consumer thread ret = pthread_create (&thread2, NULL, consumer, NULL), if (ret!=0) {printf ("Pthread_create error, [%s]\n], Strerror (ret)); return-1;} The main thread reclaims the child thread Pthread_join (thread1, NULL);p thread_join (thread2, NULL);//Release lock resource Pthread_mutex_destroy (&mutex);// Release the conditional variable resource Pthread_cond_destroy (&cond); return 0;}

Semaphore, classic consumer producer model:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include < unistd.h> #include <pthread.h> #include <semaphore.h>typedef struct node{int data;struct node *next;} node;//Chain Header node pointer nodes *head = null;sem_t sem_consumer;sem_t sem_producer;//producer thread handler void *producer (void *args) {node * Pnode = Null;while (1) {Pnode = (node *) malloc (sizeof (node)), if (pnode==null) {perror ("malloc error\n"); exit (1);} Pnode->data = rand ()%1000;//sem_producer--, if 0 is blocked sem_wait (&sem_producer);p node->next = Head;head=pnode; printf ("p:[%d]\n", Head->data);//sem_consumer++sem_post (&sem_consumer); Sleep (rand ()%3);}} Consumer threading function void *consumer (void *args) {NODE *pnode = null;while (1) {//sem_consumer--, 0 blocks sem_wait (&sem_consumer );p rintf ("c:[%d]\n", Head->data);p node = Head;head = Head->next;//sem_producer++sem_post (&sem_producer); Free (pnode);p node = null;sleep (rand ()%3);}} int main (int argc, char *argv[]) {int ret;pthread_t Thread1;pthread_t thread2;//semaphore Initialization sem_init (&sem_producer, 0, 5), Sem_init (&sem_consumer, 0, 0);//create producer thread ret = Pthread_create (&thread1, NULL, producer, NULL), if (ret!=0) {printf ("Pthread_create error, [%s]\n", Strerror (ret)); return-1;} Create a consumer thread ret = pthread_create (&thread2, NULL, consumer, NULL), if (ret!=0) {printf ("Pthread_create error, [%s]\n], Strerror (ret)); return-1;} The main thread reclaims the child thread Pthread_join (thread1, NULL);p thread_join (thread2, NULL);//Releases the Semaphore resource Sem_destroy (&sem_producer); sem_ Destroy (&sem_consumer); return 0;}

  

Linux multithreading implementation and thread synchronization function analysis

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.