Linux 多线程同步(互斥量)

/*threadrace.c*/
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int myglobal;
pthread_mutex_t work_mutex = PTHREAD_MUTEX_INITIALIZER //定义互斥量

//初始化互斥量
pthread_mutex_init(&work_mutex, NULL);

void *
thread_function (void *arg)
{
  int i, j;
  for (i = 0; i < 10; i++)
    {
      pthread_mutex_lock(&work_mutex);
      j = myglobal;
      j = j + 1;
      printf (".");
      fflush (stdout);
      sleep (1);
      myglobal = j;
      pthread_mutex_unlock(&work_mutex);
    }
  return NULL;
}

int
main (void)
{

  pthread_t mythread;
  int i;

  //创建线程
  if (pthread_create (&mythread, NULL, thread_function, NULL))//创建线程
    {
      printf ("error creating thread.");
      abort ();//终止进程
    }
  sleep(10);
  for (i = 0; i < 10; i++)
    {
      pthread_mutex_lock(&work_mutex);
      myglobal = myglobal + 1;
      printf ("o");
      fflush (stdout);
      sleep (1);
      pthread_mutex_unlock(&work_mutex);
    }

  if (pthread_join (mythread, NULL))
    {
      printf ("error joining thread.");
      abort ();
    }

  printf ("\nmyglobal equals %d\n", myglobal);

  exit (0);

}

例子2:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <semaphore.h>

void * thread_function(void * arg);
pthread_mutex_t work_mutex;

#define WORK_SIZE 1024
char work_area[WORK_SIZE];
int time_to_exit = 0;

int main(int argc, char const *argv[])
{
	int res;
	pthread_t pthread;
	void * thread_result;

	res = pthread_mutex_init(&work_mutex,NULL);
	if (res != 0)
	{
		perror("pthread_mutex_init failed!");
		exit(EXIT_FAILURE);
	}

	res = pthread_create(&pthread,NULL,thread_function,NULL);
	if (res != 0)
	{
		perror("pthread_create failed!");
		exit(EXIT_FAILURE);
	}

	pthread_mutex_lock(&work_mutex);//
	printf("input a text. Enter end to finish!\n");
	while(!time_to_exit)
	{
		fgets(work_area,WORK_SIZE,stdin);
		pthread_mutex_unlock(&work_mutex);
		while(1)
		{
			pthread_mutex_lock(&work_mutex);
			if (work_area[0] != '\0')
			{
				pthread_mutex_unlock(&work_mutex);
				sleep(1);
			}
			else
				break;
		}
	}

	pthread_mutex_unlock(&work_mutex);
//	printf("\nwaiting...");
	res = pthread_join(pthread,&thread_result);
	if (res != 0)
	{
		perror("pthread_join failed!");
		exit(EXIT_FAILURE);
	}
	printf("son thread Exit success!\n");		
	pthread_mutex_destroy(&work_mutex);
	exit(EXIT_SUCCESS);
}		
						
void * thread_function(void * arg)
{
	sleep(1);
	pthread_mutex_lock(&work_mutex);
	while(strncmp("end",work_area,3) != 0)
	{
		printf("you input %d characters\n", strlen(work_area)-1);
		work_area[0] = '\0';//in order to break the while of main thread
		pthread_mutex_unlock(&work_mutex);
		sleep(1);//in order to make the main thread get the lock
		pthread_mutex_lock(&work_mutex);
	}
	time_to_exit = 1;
	work_area[0] = '\0';	
	pthread_mutex_unlock(&work_mutex);
	pthread_exit(NULL);
}

临界资源是work_area中的内容。

你可能感兴趣的:(thread,多线程,linux,function,null,equals)