多线程编程初试

来源:互联网 发布:linux修改ssh默认端口 编辑:程序博客网 时间:2024/05/21 18:44

 主要有这么几个函数

#include <pthread.h>

 int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void *(*func) (void *),void *arg);

int pthread_join (pthread_t tid, void ** status);

pthread_t pthread_self (void);

int pthread_detach (pthread_t tid);

void pthread_exit (void *status);

 

一个小例子

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

#define BUFFSIZE 4
#define NUMBER 8

int sumOfNumber = 0;

sem_t writeResNumber;
sem_t readResNumber;

struct RecycleBuffer{
 int buffer[BUFFSIZE];
 int head, tail;
}reBuf;

pthread_mutex_t bufferMutex = PTHREAD_MUTEX_INITIALIZER;

static void *Producer (void *arg)
{
 int i;
 for (i = 0; i < NUMBER; i++)
 {
  sem_wait (&writeResNumber);
  pthread_mutex_lock (&bufferMutex);
  reBuf.buffer [reBuf.tail] = i;
  reBuf.tail = (reBuf.tail + 1) % BUFFSIZE;
  printf ("procuder %d write %d \n", pthread_self (), i);

  pthread_mutex_unlock (&bufferMutex);
  sem_post (&readResNumber);
 }
 return NULL;
}

static void *Consumer (void *arg)
{
 int i, num;

 for (i = 0; i < NUMBER; i++)
 {
  sem_wait (&readResNumber);
  pthread_mutex_lock (&bufferMutex);
  num = reBuf.buffer[reBuf.head + 1] % BUFFSIZE;
  printf ("constumer %d read %d\n", pthread_self (), num);

  pthread_mutex_unlock (&bufferMutex);
  sumOfNumber += num;
  sem_post (&writeResNumber);
 }
 return NULL;
}

int main (int argc, char *argv[])
{
 pthread_t p_tid;
 pthread_t c_tid;
 int i;

 reBuf.head = 0;
 reBuf.tail = 0;
 for (i = 0; i < BUFFSIZE; i++)
  reBuf.buffer[i] = 0;
 sem_init (&writeResNumber, 0, BUFFSIZE);
 sem_init (&readResNumber, 0, 0);

 pthread_create (&p_tid, NULL, Producer, NULL);
 pthread_create (&c_tid, NULL, Consumer, NULL);

 pthread_join (p_tid,NULL);
 pthread_join (c_tid, NULL);
 printf ("The sum of number is %d\n", sumOfNumber);
 return 0;
}

编译时需带上 pthread.a

cc 123.c -lpthread -o 123即可

原创粉丝点击