前一段时间搞了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);
}
}
本文分享了一个LINUX环境下多线程程序的实现案例。该程序通过创建多个写入和读取线程来演示线程间同步和互斥操作。使用了pthread库,并通过信号量和互斥锁来确保数据一致性。
1777

被折叠的 条评论
为什么被折叠?



