pthread的pthread_mutex_lock 的使用

参考http://haoningabc.iteye.com/blog/1709157
在c中多线程,打印数据互相不影响的例子
关键点在pthread_mutex_lock
无锁的情况
testptread.c
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include "pthread.h"

void * process(void * arg)
{
  int i;
  fprintf(stderr, "Starting process %s\n", (char *) arg);
  for (i = 0; i < 100; i++) {
       write(1, (char *) arg, 1);
//      fprintf(stdout, (char *) arg, 1);
  }
  return NULL;
}
int hello(){
        printf("hello");
        return 1;
}
int main()
{
  int retcode;
  pthread_t th_a, th_b;
  void * retval;

  retcode = pthread_create(&th_a, NULL, process, "a");
  if (retcode != 0) fprintf(stderr, "create a failed %d\n", retcode);

  retcode = pthread_create(&th_b, NULL, process, "b");
  if (retcode != 0) fprintf(stderr, "create b failed %d\n", retcode);

  retcode = pthread_join(th_a, &retval);
  if (retcode != 0) fprintf(stderr, "join a failed %d\n", retcode);

  retcode = pthread_join(th_b, &retval);
  if (retcode != 0) fprintf(stderr, "join b failed %d\n", retcode);

  return 0;
}

编译:
#!/bin/sh
gcc testptread.c -lpthread 

输出结果

a和b的打印每次输出都是不同的乱序的
-------------------------------
带锁的thread
testptread_lock.c
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include "pthread.h"
pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER;
void * process(void * arg)
{
  int i;
  fprintf(stderr, "Starting process %s\n", (char *) arg);
   pthread_mutex_lock(&mymutex);
  for (i = 0; i < 100; i++) {
       write(1, (char *) arg, 1);
//      fprintf(stdout, (char *) arg, 1);
  }
  pthread_mutex_unlock(&mymutex); 
  return NULL;
}
int hello(){
        printf("hello");
        return 1;
}
int main()
{
  int retcode;
  pthread_t th_a, th_b;
  void * retval;

  retcode = pthread_create(&th_a, NULL, process, "a");
  if (retcode != 0) fprintf(stderr, "create a failed %d\n", retcode);

  retcode = pthread_create(&th_b, NULL, process, "b");
  if (retcode != 0) fprintf(stderr, "create b failed %d\n", retcode);

  retcode = pthread_join(th_a, &retval);
  if (retcode != 0) fprintf(stderr, "join a failed %d\n", retcode);

  retcode = pthread_join(th_b, &retval);
  if (retcode != 0) fprintf(stderr, "join b failed %d\n", retcode);

  return 0;
}



无论a,b是什么时候开始,一定是一个结束之后,锁释放后, 第二个才开始
------------------------------
如果上面的访问用进程实现
则用如下


#include <stdio.h>
char buf[]={"check lock!\n"};
int main(int argc,char *argv[]){
    int i,p1,p2,fd;
    fd=creat("lock.dat",0644);
    write(fd,buf,20);
    while((p1=fork())==-1);
    if(p1==0){
        lockf(fd,1,0);
        for(i=1;i<=3;i++){
            printf("child1!\n");
        }
        lockf(fd,0,0); 
    }else{
        while((p2=fork())==-1);
        if(p2==0){
            lockf(fd,1,0);
            for(i=1;i<=4;i++){
                printf("child2!\n");
            }
            lockf(fd,0,0);
        }else{
            printf("parrent!\n");
        }
    }
    close(fd);
}

猜你喜欢

转载自haoningabc.iteye.com/blog/2021766