pthread_mutex_init函数《代码》

来源:互联网 发布:sql while循环 编辑:程序博客网 时间:2024/06/10 00:27
/*
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex, constpthread_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);

在使用互斥锁前,需要定义互斥锁(全局变量),定义互斥锁对象形式为:
     pthread_mutex_t lock;
pthread_mutex_init() 函数中:
第一个参数 mutex 是指向要初始化的互斥锁的指针。
第二个参数 mutexattr 是指向属性对象的指针,该属性对象定义要初始化的互斥锁的属性。如果该指针为 NULL,则使用默认的属性。

此外,还可以用宏 PTHREAD_MUTEX_INITIALIZER 来初始化静态分配的互斥锁,如下:
   pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

对于静态初始化的互斥锁,不需要调用 pthread_mutex_init() 函数。
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
  
void*function(void*arg);
pthread_mutex_t mutex;
intcounter = 0;
intmain(intargc, char*argv[])
{
    intrc1,rc2;
      
    char*str1="wenhaoll";
    char*str2="linglong";
    pthread_t thread1,thread2;
  
    pthread_mutex_init(&mutex,NULL);
    if((rc1 = pthread_create(&thread1,NULL,function,str1)))
    {
        fprintf(stdout,"thread 1 create failed: %d\n",rc1);
    }
  
    if(rc2=pthread_create(&thread2,NULL,function,str2))
    {
        fprintf(stdout,"thread 2 create failed: %d\n",rc2);
    }
  
    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    return0;
}
  
void*function(void*arg)
{
    char*m;
    m = (char*)arg;
    pthread_mutex_lock(&mutex);
    while(*m !='\0')
    {
        printf("%c",*m);
        fflush(stdout);
        m++;
        sleep(1);
    }
    printf("\n");
    pthread_mutex_unlock(&mutex);
}

原创粉丝点击