欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

用Linux多线程(C语言)打造:基于信号量的线程安全队列实例

最编程 2024-07-25 07:11:19
...
  • /*
  •  * \File
  •  * main.c
  •  * \Breif
  •  * Thread-safe circular-queue implemented by semaphore
  •  * \Author
  •  * Hank.yan
  •  */
  • #include <stdio.h>
  • #include <stdlib.h>
  • #include <unistd.h>
  • #include <string.h>
  • #include <pthread.h>
  • #include <semaphore.h>

  • #include "cir_queue.h"

  • void* thread_queue(void *arg);

  •     
  • /*
  •  * \Func
  •  * main
  •  */
  • int main(int argc, char* argv[])
  • {
  •   int res;
  •   cir_queue_t cq;
  •   DataType e;
  •  
  •   pthread_t a_thread, b_thread;
  •   void* thread_result;

  •   init_cir_queue(&cq);

  •   push_cir_queue(&cq, 1);
  •   push_cir_queue(&cq, 2);
  •   push_cir_queue(&cq, 3);

  •   print_queue(&cq);

  •   res = pthread_create(&a_thread, NULL, thread_queue, (void*)&cq);
  •   if (res != 0)
  •   {
  •     perror("Thread creation failed.");
  •     exit(EXIT_FAILURE);
  •   }

  •   e = pop_cir_queue(&cq);    
  •   e = pop_cir_queue(&cq);    
  •   print_queue(&cq);

  •   push_cir_queue(&cq, 9);
  •   push_cir_queue(&cq, 100);

  •   print_queue(&cq);

  •   res = pthread_create(&b_thread, NULL, thread_queue, (void*)&cq);
  •   if (res != 0)
  •   {
  •     perror("Thread creation failed.");
  •     exit(EXIT_FAILURE);
  •   }
  •   e = pop_cir_queue(&cq);    


  •   push_cir_queue(&cq, 20);
  •   print_queue(&cq);

  •   printf("Waiting for thread to finish...\n");
  •   res = pthread_join(a_thread, &thread_result);
  •   if (res != 0)
  •   {
  •     perror("Thread join failed.");
  •     exit(EXIT_FAILURE);
  •   }
  •   print_queue(&cq);

  •   printf("Waiting for thread to finish...\n");
  •   res = pthread_join(b_thread, &thread_result);
  •   if (res != 0)
  •   {
  •     perror("Thread join failed.");
  •     exit(EXIT_FAILURE);
  •   }

  •   destroy_cir_queue(&cq);

  •   printf("Thread joined, it returned %s\n", (char*)thread_result); 
  •   exit(EXIT_SUCCESS);
  • }


  • void *thread_queue(void *cirqueue)
  • {
  •   int flag;
  •   DataType element;

  •   print_queue((cir_queue_t*)cirqueue);

  •   flag = is_empty_cir_queue((cir_queue_t*)cirqueue);

  •   print_queue((cir_queue_t*)cirqueue);
  •   element = pop_cir_queue((cir_queue_t*)cirqueue);
  •   element = pop_cir_queue((cir_queue_t*)cirqueue);
  •   print_queue((cir_queue_t*)cirqueue);

  •   push_cir_queue((cir_queue_t*)cirqueue, 5);
  •   print_queue((cir_queue_t*)cirqueue);

  •   push_cir_queue((cir_queue_t*)cirqueue, 99);
  •   push_cir_queue((cir_queue_t*)cirqueue, 1000);
  •   push_cir_queue((cir_queue_t*)cirqueue, 88);

  •   print_queue((cir_queue_t*)cirqueue);
  •   
  •   pthread_exit("Thank you for the cpu time.");
  • }
  • 推荐阅读