歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux服務器

Linux多線程的知識介紹

今天再一次看了下Linux多線程的知識。看了看代碼是怎麼實現的,很high。再詳細的看一下這幾段代碼

  關於線程很細致的解釋百度百科上寫的相當好了。有時間我還得看幾遍。地址:百度百科--Linux多線程

  /*

  *生產者消費者問題的多線程互斥控制,源程序出自《Linux網絡編程》

  */

  #include <stdio.h>

  #include <pthread.h>

  #include <sched.h>

  void *producter_f(void *arg);

  void *consumer_f(void *arg);

  int buffer_has_item = 0; /*設置緩存數量*/

  pthread_mutex_t mutex; /*設置互斥*/

  int running = 1;

  int main (void)

  {

  pthread_t consumer_t; /*線程參數*/

  pthread_t producter_t;

  /*不知道這句為什麼不給我變藍色,初始化互斥*/

  pthread_mutex_init(&mutex, NULL);

  /*創建線程*/

  pthread_create(&producter_t, NULL, (void *)producter_f, NULL);

  pthread_create(&consumer_t, NULL, (void *)consumer_f, NULL);

  usleep(1);

  running = 0;

  /*等待線程退出,一個線程不能夠被多個線程等待*/

  pthread_join(consumer_t, NULL);

  pthread_join(producter_t, NULL);

  /*銷毀互斥*/

  pthread_mutex_destroy(&mutex);

  return 0;

  }

  void *producter_f(void *arg)

  {

  while (running)

  {

  pthread_mutex_lock(&mutex); /*加鎖,進入互斥區*/

  buffer_has_item++;

  printf("product ,num:%d\n", buffer_has_item);

  pthread_mutex_unlock(&mutex); /*解鎖,離開互斥區*/

  }

  }

  void *consumer_f(void *arg)

  {

  while (running)

  {

  pthread_mutex_lock(&mutex);

  buffer_has_item--;

  printf("consumer,num:%d\n",buffer_has_item);

  pthread_mutex_unlock(&mutex);

  }

  }

  /*

  *生產者消費者問題的信號量控制,可以與上述程序進行對比,出處--同上

  */

  #include <stdio.h>

  #include <pthread.h>

  #include <semaphore.h>

  void *producter_f(void *arg);

  void *consumer_f(void *arg);

  sem_t sem;

  int running = 1;

  int main (void)

  {

  pthread_t consumer_t;

  pthread_t producter_t;

  sem_init(&sem, 0, 16); /*信號量初始化*/

  pthread_create(&producter_t, NULL, (void*)producter_f, NULL);

  pthread_create(&consumer_t, NULL, (void *)consumer_f, NULL);

  sleep(1);

  running = 0;

  pthread_join(consumer_t, NULL);

  pthread_join(producter_t, NULL);

  sem_destroy(&sem); /*銷毀信號量*/

  return 0;

  }

  void *producter_f(void *arg)

  {

  int semval = 0; /*信號量的初始值*/

  while (running)

  {

  usleep(1);

  sem_post(&sem); /*信號量+1*/

  sem_getvalue(&sem, &semval);/*得到信號量的值*/

  printf("pro,num:%d\n",semval);

  }

  }

  void *consumer_f(void *arg)

  {

  int semval = 0;

  while (running)

  {

  usleep(1);

  sem_wait(&a12下一頁

Copyright © Linux教程網 All Rights Reserved