Simple application of Semaphore, Mutex ,MultiThreading in Linux

I had been working on a little task assigned by the teacher of Embedded Operation System . Now I am gald to share

some knowledge during my development process .  Because the control flow of the application was draw by the

teacher . All I needed to do is implementing those procedures show below.



Ok , at first glance , what I thought was following the procedures to code . Since I'd been reading <Efficitive C++> ,

I decided to construct my own class to seal the operations in controling pipe . Here is the code(pipe.h):

#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<errno.h>
class self_pipe{
	/* create a named pipe , mode=1 read ,mode=2 write*/	
public:
	self_pipe(const char * pName,const int mode)
	:pipeName(pName),
	pipe_fd(0),
	write_mode(O_WRONLY),
	read_mode(O_RDONLY),
	open_mode(mode),
	buf_size(4096),
	buffer(0){init();}
	
	
	~self_pipe();
	
	/* passing the address of the buffer and size of the buffer 
	   to write string to the pipe ;the return value is equal to standard function
	   write()
	*/
	const int Pwrite(const char * buf,const int bufSize);
	
	/* read string from the pipe ,on success ,it returns the pointer to the string
	   otherwise 0 was returned .
	*/
	const char* Pread();

	
	
private:
	const char * pipeName;
	int 	 pipe_fd;
	const int 	 write_mode;
	const int 	 read_mode ;
	int 	 open_mode;
	const int 	 buf_size;
	char * buffer;
	void init();
};

void self_pipe::init()
{
	/* chose which operation to perform on the pipe :
		read or write 
	*/
	if(open_mode == 1)
		open_mode=read_mode|O_NONBLOCK;
	else if(open_mode == 2)
		open_mode=write_mode;
	else {
		printf("Error while constructing name pipe\nCheck you mode please\n");
		exit(0) ;
	}
	
	/* testing whether the named pipe was exist ,if not , create the corresponding
		pipe using the given name .
	*/
	if(access(pipeName,F_OK) == -1){
		if( mkfifo(pipeName,0777) != 0){
			printf("Error while creating a pipe file\nExit !\n");
			exit(0);
		}
	}
	
	/* open the pipe with mode initilized above */
	pipe_fd=open(pipeName,open_mode);
}

self_pipe::~self_pipe()
{
	if(buffer != 0)
		free(buffer);
	close(pipe_fd);
}

const int self_pipe::Pwrite(const char * buf,const int bufSize)
{
	return write(pipe_fd,buf,bufSize);
}

const char * self_pipe::Pread()
{
	/* create a buffer on the first time it was called */
	if(buffer == 0 )
		buffer=(char*)malloc(sizeof(char)*buf_size);
	if(read(pipe_fd,buffer,buf_size)>0){
		return buffer;}
	else
		return 0;
}

I wrote comments in the codes . So I won't explain how this class work . If you don't understand my codes or have any doubt , don't hesitate to contact me . 

After design and code this pipe class , I jumped to implement Multithreading . The reason why I jumped over

Semaphore is that I didn't had previous experience about this technique . So , let me show you how to create

multiple threads and control their behaviors by Mutex technique in Linux platform .

First of all , you need to define two global struct variables:

pthread_mutex_t mutex/*=PTHREAD_MUTEX_INITIALIZER*/;
pthread_mutexattr_t mutexAttr;

The first variable "mutex" is the Mutex itself  . It controls the thread's behaviors . And the next variable mutexAttr was

used to set the properties of the mutex . Here goes the codes that create two threads :

        //init the mutex's attribution to PTHREAD_MUTEX_ERRORCHECK
	pthread_mutexattr_init(&mutexAttr);
	pthread_mutexattr_settype(&mutexAttr,PTHREAD_MUTEX_ERRORCHECK);
	
	//init the mutex with the initilized attribution variable
	if(pthread_mutex_init(&mutex,&mutexAttr)==0)
	{
		pthread_t t1,t2;
                //create two threads 
                pthread_create(&t1,NULL,&producer,NULL);
		pthread_create(&t2,NULL,&customer,NULL);
		printf("two threads have been created\n");
		pthread_join(t1,NULL);
		pthread_join(t2,NULL);

                //destroy the mutex and its attribution variable on exit
                pthread_mutexattr_destroy(&mutexAttr);
		pthread_mutex_destroy(&mutex);
	}
	else
	{
		printf("Init mutex failed !Error code=%d\n",errno);
	}

And the thread function should be defined as following:

void * customer(void *arg);
void * producer(void *arg);

I thought codes are easier to explain what they do , so I would let you to consume them by yourself .

Well , it's late now . I got to wash my clothes and I would post the remaining of this passage tomorrow ,I guess.

So , catch you later . 微笑


猜你喜欢

转载自blog.csdn.net/cwg2552298/article/details/79822740