Thread------Competition, mutex---multithreading to the same file read and write problems

Source: Internet
Author: User
Tags rewind

When multiple control threads share the same memory, you need to ensure that each thread sees a consistent view of the data.

If the variables used by each thread are not read and modified by other threads, then there is no problem of consistency.

The thread mutex is used to protect data and to ensure that only one thread accesses the data at the same time.

Mutex: Restrict Code---Exclusive

A long time ago:

The following program has a competition problem yo, when creating 20 threads, each thread to read and write to the same file, it is possible to have n threads open and read the file at the same time, the writing process may be repeated for the same number of +1 operations. For example, read to 1, then n threads fetch 1 and 1 This number do +1 operation.

/*implement 20 threads to write to/tmp/out +1 operation problem: Run result should be 21, for multi-core device, running will be competitive, running result is uncertain (multiple threads open file)*/#include<stdio.h>#include<stdlib.h>#include<pthread.h>#include<string.h>#defineThrnum 20//Number of Threads#defineMAXLINE 1024//The maximum number of bytes read from a file#defineFILENAME "/tmp/out"void* Thr_add (void*p) {FILE*FP; CharLinebuf[maxline]; //Openfp = fopen (FILENAME,"r+"); if(fp = =NULL) {Perror ("fopen ()"); Exit (1); }       //Readfgets (LINEBUF,MAXLINE,FP); //WriteRewind (FP);//file offset device file start locationfprintf (FP,"%d\n", Atoi (LINEBUF) +1); //Closefclose (FP); Pthread_exit (NULL);}intMain () {intI, err;    pthread_t Tid[thrnum]; //Creating Threads     for(i =0; i < Thrnum; i++) {Err= Pthread_create (tid+i,null,thr_add,null); if(Err) {fprintf (stderr,"pthread_create ():%s\n", Strerror (err)); Exit (1); }       }       //Corpse     for(i =0; i < Thrnum; i++) {pthread_join (tid[i],null); }   
View Code

The solution: it's mutual exclusion.

Mutex creation

       int Pthread_mutex_destroy (pthread_mutex_t *mutex); //Mutex destruction       int pthread_mutex_init (pthread_mutex_t *restrict Mutex,const pthread_mutexattr_t * Restrict attr); //Dynamic initialization: Parameter 1: variable; parameter 2: property;       pthread_mutex_t mutex = Pthread_mutex_initializer; //Static initialization

Lock and Unlock:

       int pthread_mutex_lock (pthread_mutex_t *mutex); //Blocking       int pthread_mutex_trylock (pthread_mutex_t *mutex); //       int pthread_mutex_unlock (pthread_mutex_t *mutex); //Unlock

So, the program is modified to: Add a lock to him

#include <pthread.h>#include<string.h>#defineThrnum 20//Number of Threads#defineMAXLINE 1024//The maximum number of bytes read from a file#defineFILENAME "/tmp/out"Staticpthread_mutex_t mut = Pthread_mutex_initializer;//Define a lockvoid* Thr_add (void*p) {FILE*FP; CharLinebuf[maxline]; //Openfp = fopen (FILENAME,"r+"); if(fp = =NULL) {Perror ("fopen ()"); Exit (1); } pthread_mutex_lock (&mut); //Readfgets (LINEBUF,MAXLINE,FP); //WriteRewind (FP);//file offset device file start locationfprintf (FP,"%d\n", Atoi (LINEBUF) +1); //Closefclose (FP); Pthread_mutex_unlock (&mut); Pthread_exit (NULL);}intMain () {intI, err;    pthread_t Tid[thrnum]; //Creating Threads     for(i =0; i < Thrnum; i++) {Err= Pthread_create (tid+i,null,thr_add,null); if(Err) {fprintf (stderr,"pthread_create ():%s\n", Strerror (err)); Exit (1); }       }       //Corpse     for(i =0; i < Thrnum; i++) {pthread_join (tid[i],null); } Pthread_mutex_destroy (&mut);//Destroy MutexExit0);}
View Code

Ok!

Thread------Competition, mutex---multithreading to the same file read and write problems

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.