Linux thread synchronization operation instance

Source: Internet
Author: User

1: Linux thread Introduction

If you only need to terminate a thread without terminating the entire process, there are three methods:
Return from the thread function. This method is not applicable to the main thread. Return from the main function is equivalent to calling exit.
One thread can call pthread_cancel to terminate another thread in the same process.
The thread can call pthread_exit to terminate itself.
# Include <pthread. h>

Void pthread_exit (void * value_ptr );
Value_ptr is of the void * type. It is used in the same way as the return value of the thread function. Other threads can call pthread_join to obtain this pointer.
Note that the memory unit pointed to by the pointer returned by pthread_exit or return must be global or allocated by malloc,
The thread function cannot be allocated on the stack of the thread function, because the thread function has exited when other threads get the returned pointer.
# Include <pthread. h>
Int pthread_join (pthread_t thread, void ** value_ptr );
Returned value: 0 is returned for success, and an error number is returned for failure.
The thread that calls this function will wait until the thread whose ID is thread terminates.
The thread is terminated in different ways. The termination status obtained through pthread_join is different,

Summary: If the thread returns through return, the returned value of the thread function is stored in the Unit pointed to by value_ptr. If the thread is terminated abnormally when another thread calls pthread_cancel, the constant pthread_canceled is stored in the Unit pointed to by value_ptr.

If the thread calls pthread_exit to terminate, the units pointed to by value_ptr store the parameters passed to pthread_exit.

The following examples describe simple APIs:

void *thr_fn1(void *arg){printf("thread 1 returning\n");return (void *)100;}void *thr_fn2(void *arg){printf("thread 2 exiting\n");pthread_exit((void *)200);}void *thr_fn3(void *arg){while(1){printf("thread 3 writing\n");sleep(1);}}void threadexitstatus(){pthread_t tid; void *tret;pthread_create(&tid, NULL, thr_fn1, NULL);pthread_join(tid, &tret);printf("thread 1 exit code %d\n", (int)tret);pthread_create(&tid, NULL, thr_fn2, NULL);pthread_join(tid, &tret);printf("thread 2 exit code %d\n", (int)tret);pthread_create(&tid, NULL, thr_fn3, NULL);sleep(3);pthread_cancel(tid);pthread_join(tid, &tret);printf("thread 3 exit code %d\n", (int)tret);return 0;/*[root@localhost /wlan/plc/workspace/signatest/Debug]$./signatest 3thr_fn1 pid 13323 tid 3078593392 (0xb77f9b70)thread 1 returningthread 1 exit code 100thr_fn2 pid 13323 tid 3078593392 (0xb77f9b70)thread 2 exitingthread 2 exit code 200thr_fn3 pid 13323 tid 3078593392 (0xb77f9b70)thread 3 writingthread 3 writingthread 3 writingthread 3 exit code -1[root@localhost /wlan/plc/workspace/signatest/Debug]$ */}


2: Linux: Conditional Variable

Thread A needs to wait for a condition to be established before it can continue to run. If this condition is not true, thread a will block the wait,
When thread B sets this condition during execution, thread a is awakened to continue execution.
In the pthread library, conditional variables are used to block waiting for a condition or wake up the thread waiting for this condition.
Condition variable is represented by a variable of the pthread_cond_t type, which can be initialized and destroyed as follows:

# Include <pthread. h>
Int pthread_cond_destroy (pthread_cond_t * Cond );
Int pthread_cond_init (pthread_cond_t * restrict cond, const pthread_condattr_t * restrict ATTR );
Pthread_cond_t cond = pthread_cond_initializer;
Return Value: 0 is returned for success, and an error number is returned for failure. Similar to mutex initialization and destruction, the pthread_cond_init function initializes a condition variable. If the ATTR parameter is null, it indicates the default attribute. The pthread_cond_destroy function destroys a condition variable. If conditionvariable is statically allocated, you can also use a macro to define pthead_cond_initializer initialization, which is equivalent to using the pthread_cond_init function initialization and the ATTR parameter is null.
# Include <pthread. h>
Int pthread_cond_timedwait (pthread_cond_t * restrict cond, pthread_mutex_t * restrict mutex, const struct timespec * restrict abstime );
Int pthread_cond_wait (pthread_cond_t * restrict cond, pthread_mutex_t * restrict mutex); int pthread_cond_broadcast (pthread_cond_t * Cond );
Int pthread_cond_signal (pthread_cond_t * Cond );
Return Value: 0 is returned for success, and an error number is returned for failure.
It can be seen that a condition variable is always used with a mutex. The pthread_cond_timedwait function also has an additional parameter that can be set to wait for timeout. If no other thread can wake up the current thread at the time specified by abstime, etimedout is returned.
One thread can call pthread_cond_signal to wake up another thread waiting on a certain condition variable, or call pthread_cond_broadcast to wake up all threads waiting on this condition variable.

// Initialize the conditional variables and mutex.

static pthread_mutex_t pthreadmtx = PTHREAD_MUTEX_INITIALIZER;static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;static int avail = 0;static int productNum = 0;static void * threadFunc(void *arg){    int cnt = atoi((char *) arg);    int s, j;    printf("need Num:%d \n",cnt);    while(1)    {      usleep(2);//    sleep(2); //   sleep(1);        /* Code to produce a unit omitted */        s = pthread_mutex_lock(&pthreadmtx);        if (s != 0)            errExitEN(s, "pthread_mutex_lock");        avail++;        /* Let consumer know another unit is available */        productNum++;        printf("Num Product:%d\n",productNum);        s = pthread_mutex_unlock(&pthreadmtx);        if (s != 0)            errExitEN(s, "pthread_mutex_unlock");        s = pthread_cond_signal(&cond);         /* Wake sleeping consumer */        if (s != 0)            errExitEN(s, "pthread_cond_signal");    }    return NULL;}void threadConditionMutex(int argc, char *argv[]){    pthread_t tid;    int s, j;    int totRequired;            /* Total number of units that all threadswill produce */    int numConsumed;            /* Total units so far consumed */    Boolean done;    time_t t;    struct timespec request;    struct timeval start;    t = time(NULL);    /* Create all threads */    totRequired = 0;    {        totRequired += atoi(argv[1]);        s = pthread_create(&tid, NULL, threadFunc, argv[1]);        if (s != 0)            errExitEN(s, "pthread_create");    }    /* Use a polling loop to check for available units */    numConsumed = 0;    done = FALSE;    for (;;)    {        s = pthread_mutex_lock(&pthreadmtx);        if (s != 0)            errExitEN(s, "pthread_mutex_lock");        if (gettimeofday(&start, NULL) == -1)            errExit("gettimeofday");        request.tv_sec = start.tv_sec+1;        request.tv_nsec = start.tv_usec*1000;     //   s = pthread_cond_wait(&cond, &pthreadmtx);        s = pthread_cond_timedwait(&cond, &pthreadmtx,&request);        if (s == 0)        {        /* Consume all ava *ilable units*/            numConsumed ++;            avail--;            printf("T=%ld: numConsumed=%d avail:%d\n", (long) (time(NULL) - t),numConsumed,avail);            done = numConsumed >= totRequired;        }        else        {        printf("pthread_cond_timedwait timeout...............\n");        }        s = pthread_mutex_unlock(&pthreadmtx);        if (s != 0)            errExitEN(s, "pthread_mutex_unlock");        if (done)            break;        usleep(200);    }    exit(EXIT_SUCCESS);}


3: Linux semaphore

Similar to mutex, semaphore indicates the number of available resources. Unlike mutex, this number can be greater than 1.
POSIX semaphore semaphores can be used not only for synchronization between threads of the same process, but also for synchronization between different processes.
# Include <semaphore. h>
Int sem_init (sem_t * SEM, int pshared, unsigned int value );
Int sem_wait (sem_t * SEM );
Int sem_trywait (sem_t * SEM );
Int sem_post (sem_t * SEM );
Int sem_destroy (sem_t * SEM );
The semaphore variable is of the sem_t type, and sem_init () initializes a semaphore variable. The value parameter indicates the number of available resources,
The pshared parameter is 0, indicating that the semaphores are used for synchronization between threads of the same process,
After using the semaphore variable, you should call sem_destroy () to release resources related to semaphore.
You can call sem_wait () to obtain resources and reduce the semaphore value by 1. If the semaphore value is 0 when sem_wait () is called,
Then wait. If you do not want to suspend the wait, you can call sem_trywait ().
You can call sem_post () to release resources, add the value of semaphore to 1, and wake up the suspended thread.

The sample code is as follows:

#include <semaphore.h>#define NUM 5int queue[NUM];sem_t blank_number, product_number;int product_num =0;int consum_num =0;void *producer(void *arg){ int p = 0;while (1){sem_wait(&blank_number);queue[p] = p;printf("Produce %d\n", queue[p]);product_num++;sem_post(&product_number);p = (p+1)%NUM;sleep(1);}}void *consumer(void *arg){int c = 0;while (1){sem_wait(&product_number);printf("Consume %d\n", queue[c]);queue[c] = 0;consum_num++;sem_post(&blank_number);c = (c+1)%NUM;sleep(1);}}void semtest(){pthread_t pid, cid;sem_init(&blank_number, 0, NUM);sem_init(&product_number, 0, 2);pthread_create(&pid, NULL, producer, NULL);sleep(4);pthread_create(&cid, NULL, consumer, NULL);while(1){printf("product_num:%d \t consum_num:%d avail:%d\n",product_num,consum_num,(product_num-consum_num));sleep(1);}pthread_join(pid, NULL);pthread_join(cid, NULL);sem_destroy(&blank_number);sem_destroy(&product_number);return 0;}



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.