Use mutex to solve producer and consumer problems

Source: Internet
Author: User
Mutex lock: Lock and unlock

Mutex locks refer to mutual exclusion and are the most basic synchronization form. They can be used to protect the critical fetch to ensure that only one thread is executing the code at any time. It can be used to synchronize various threads in a process. If the mutex lock is stored in a memory area shared by multiple processes, it can also be used for synchronization between these processes. It actually protects the data manipulated in the critical section, that is, the shared data shared by multiple threads or processes.


Usage

Lock_the_mutex (...)

Critical Section

Unlock_the_mutex (,,,)

In POSIX, mutex locks declare variables of the pthread_mutex_t data type.


Related functions

# Include <pthread. h>

Int pthread_mutex_init (pthread_mutex_t * mutex, const pthread_mutexattr_t * mutexattr) // dynamically create

Int pthread_mutex_destroy (pthread_mutex_t * mutex) // destroy the mutex.

Int pthread_mutex_lock (pthread_mutex_t * mutex); // lock

Int pthread_mutex_trylock (pthread_mutex_t * mutex); // unlock non-blocking

Int pthread_mutex_unlock (pthread_mutex_t * mutex); // block and unlock

If you try to lock a mutex lock that has been locked by a thread, pthread_mutex_lock will block the lock until it is unlocked. Pthread_mutex_trylock is a non-blocking function. If the mutex is locked. It returns an ebusy error.

Solving producer and consumer problems

Multiple producers and one consumer, such


The integer array buff contains the items to be produced and consumed (that is, shared data), and the buff data increases progressively from 0.

Global variables shared between threads


Set concurrent Thread level

Call pthread_setconcurrency. This function is required when we want each of the multiple producer threads to have an execution opportunity.

Command Line Parameters

The first command line parameter specifies the number of items stored by the producer, and the next parameter specifies the number of producer threads to be created.


Specific implementation code

#include <pthread.h>#include <sys/types.h>#include <stdio.h>#include <stdlib.h>#define MAXNITEMS  10000#define MAXNTHREADS 20int nitems;    //read-only by producer and consumerstruct {pthread_mutex_t  mutex;int buff[MAXNITEMS];int nput;int nval;}shared =        //initialized staticly{PTHREAD_MUTEX_INITIALIZER};void *producer(void *);void *consumer(void *);int min(int a, int b) { return a<b ? a : b; }int main(int argc, char *argv[]){int i, nthreads, count[MAXNTHREADS];pthread_t tid_produce[MAXNTHREADS], tid_consume;if(argc!=3){printf("usage: ProCon <#items> <#threads>");exit(1);}nitems = min(atoi(argv[1]), MAXNITEMS);nthreads = min(atoi(argv[2]), MAXNTHREADS);pthread_setconcurrency(nthreads);for(i=0; i<nthreads; i++){count[i] = 0;pthread_create(&tid_produce[i], NULL, producer, &count[i]);}//wait for all the producer threadsfor(i=0; i<nthreads; i++){pthread_join(tid_produce[i], NULL);printf("count[%d] = %d\n", i, count[i]);}//start, then wait for the consumer threadpthread_create(&tid_consume, NULL, consumer, NULL);pthread_join(tid_consume, NULL);return 0;}void *producer(void * arg){for(; ; ){pthread_mutex_lock(&shared.mutex);if(shared.nput >= nitems){pthread_mutex_unlock(&shared.mutex);return (NULL);//array is full, we're done}shared.buff[shared.nput] = shared.nval;shared.nput++;shared.nval++;pthread_mutex_unlock(&shared.mutex);*((int *)arg) += 1;}}void *consumer(void *arg){int i;for(i=0; i<nitems; i++){if(shared.buff[i]!=i){printf("buff[%d] = %d\n", i, shared.buff[i]);}}return NULL;}

Code explanation

Line 39-42 is used to create a consumer thread. Each thread executes the producer function and saves the thread ID of each thread in the tid_produce array. Wait until all producer threads are finished and start the consumer thread again. Output The Count value of each thread at the end of the producer thread, that is, the number of thread executions.

Note: The addition of the count element does not belong to the critical section, because each thread has its own counter.

The running result is as follows:


If the mutex lock is removed, the error value of the buff will be output (when the items compare the size ),

My test results on Ubuntu./procon 400 5


Note: This blog post is <UNIX network programming-Volume 2> Reading Notes

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.