LINUX下的多线程框架

来源:互联网 发布:淘宝高档晚礼服 编辑:程序博客网 时间:2024/06/14 00:14

前一段时间搞了LINUX的多线程。下面把源代贴出来,雅谷共享:

#include  <stdio.h>
#include  <string.h>
#include  <iostream>
#include "time.h"
#include "adatetime.h"
#include <pthread.h>
#include  <vector>
#include  <sstream>
#include  <stdio.h>
#include  <unistd.h>
#include  <semaphore.h>

using namespace std;
vector <string> Record;
void * Write_Thread(void * arg);
void * Read_Thread(void *arg);

sem_t bat_sem;

pthread_mutex_t decompress_mutex;

main()
{
 pthread_t a_thread;
 pthread_t b_thread;
 pthread_t c_thread;
 pthread_t d_thread;
 
 TIMETYPE timeType;
 getmytime( &timeType );
 char time[ 11 ];
 memset( time , 0 , sizeof( time ) );
 sprintf( time , "[%2d:%2d:%2d]" , timeType.hour , timeType.min , timeType.sec );
 cout << time << "hello the new unix programmers' world!" << endl;
 
 pthread_mutex_init(&decompress_mutex, NULL);
 sem_init(&bat_sem, 0, 0);
 
 int i=100;
 pthread_create(&a_thread, NULL, Write_Thread, (void *)(&i));
 sleep(1);
 i=200;
 pthread_create(&b_thread, NULL, Write_Thread, (void *)(&i));
 sleep(1);
 i=300;
 pthread_create(&c_thread, NULL, Write_Thread, (void *)(&i));
 sleep(1);
 pthread_create(&d_thread, NULL, Read_Thread, NULL);
 sleep(1);
 pthread_create(&d_thread, NULL, Read_Thread, NULL);
 sleep(1);
 pthread_create(&d_thread, NULL, Read_Thread, NULL);
 int c=getchar();
 
 pthread_mutex_destroy(&decompress_mutex);
 
 
}
void * Write_Thread(void * arg)
{
 while (true)
 {
  int count=*((int *)arg);
  for (int i=(count-100);i<=count;i++)
  {
   ostringstream buf;
   buf<<i;
   pthread_mutex_lock(&decompress_mutex);
   Record.push_back(buf.str());
   
   pthread_mutex_unlock(&decompress_mutex);
   sem_post(&bat_sem);
  }
 }
}
void * Read_Thread(void *arg)
{
 sem_wait(&bat_sem);
 while (true)
 {
  int count=Record.size();
  cout << "大小:" << count << endl;
  //for (int i=1;i<=count;i++)
  //{
   pthread_mutex_lock(&decompress_mutex);
   vector<string>::iterator it=Record.begin();
   cout << "TEST:" << (*it) << endl;
   Record.erase(it);
   //it++;
   pthread_mutex_unlock(&decompress_mutex);
  //}
  sem_wait(&bat_sem);
 }
}