新手求助~如何实现随机启动线程?
我参考网上搜索到的资料写了一个生产者消费者问题的小程序:
#include<iostream.h>
#include<windows.h>
#include<time.h>
#include <stdio.h>
const int size = 5; //缓冲区大小
const int producer_count = 5; //生产者线程个数
const int consumer_count = 5; //消费者线程个数
const int thread_count = producer_count + consumer_count; //总线程个数
int in = 0; //缓冲区的生产者下标
int out = 0; //缓冲区的消费者下标
int buffer[size]; //缓冲区
int product_num = 0;//生产流水号
int consume_num = 0;//消费流水号
HANDLE hmutex;
HANDLE hempty;
HANDLE hfull;
void produce();
void consume();
DWORD WINAPI producer(LPVOID lpParamer)
{
while(true)
{
WaitForSingleObject(hempty,INFINITE);
WaitForSingleObject(hmutex,INFINITE);
produce();
Sleep(1000);
ReleaseMutex(hmutex);
ReleaseSemaphore(hfull,1,NULL);
}
return 0;
}
DWORD WINAPI consumer(LPVOID lpParamer)
{
while(true)
{
WaitForSingleObject(hfull,INFINITE);
WaitForSingleObject(hmutex,INFINITE);
consume();
Sleep(1000);
ReleaseMutex(hmutex);
ReleaseSemaphore(hempty,1,NULL);
}
return 0;
}
void main()
{
hmutex = CreateMutex(NULL,false,NULL);
hempty = CreateSemaphore(NULL,size,size,NULL); //不确定:初值是size还是size-1,最大值同样不确定
hfull = CreateSemaphore(NULL,0,size,NULL);
HANDLE PThreads[producer_count];//生产者线程的句柄
HANDLE CThreads[consumer_count];//消费者线程的句柄
DWORD producerID[producer_count]; //生产者线程的标识符
DWORD consumerID[consumer_count]; //消费者线程的标识符
int i = 0;
int j = 0;
for(i=0;i<5;i++)
{
PThreads[i] = CreateThread(NULL,0,producer,NULL,0,&producerID[i]);
}
for(j=0;j<5;j++)
{
CThreads[j] = CreateThread(NULL,0,consumer,NULL,0,&consumerID[j]);
}
bool g_continue = true;
while(g_continue){
if(getchar())
{ //按回车后终止程序运行
g_continue = false;
}
}
}
void produce()
{
cout<<"生产第"<<product_num<<"号产品"<<endl;
buffer[in] = product_num;
in = (in + 1) % size;
product_num++;
}
void consume()
{
consume_num = buffer[out];
cout<<"消费第"<<consume_num<<"号产品"<<endl;
out = (out + 1) % size;
}
但是生产和消费的都是固定顺序的:
生产
生产
生产
生产
生产
消费
消费
消费
消费
消费
我想要能够改成随机启动生产者或是消费者的线程,比如:
生产
生产
消费
生产
消费
消费
...
是的生产和消费的顺序不是固定的,而是随机的,请问应该如何实现?
非常感谢! 多线程
[解决办法]
for(i=0;i<5;i++)
{
PThreads[i] = CreateThread(NULL,0,producer,NULL,0,&producerID[i]);
}
for(j=0;j<5;j++)
{
CThreads[j] = CreateThread(NULL,0,consumer,NULL,0,&consumerID[j]);
}
你代码里写的就是按顺序的,当然就是按顺序的了
for(i=0, j=0;i<5
[解决办法]
j< 5;)
{
if (i>=5)
{
CThreads[j] = CreateThread(NULL,0,consumer,NULL,0,&consumerID[j]);
j++;
}
else if (j>=5)
{
PThreads[i] = CreateThread(NULL,0,producer,NULL,0,&producerID[i]);
i++;
}
else
{
int n = rand()%2;
if (n == 0)
{
PThreads[i] = CreateThread(NULL,0,producer,NULL,0,&producerID[i]);
i++;
}
else
{
CThreads[j] = CreateThread(NULL,0,consumer,NULL,0,&consumerID[j]);
j++;
}
}
}
这只是思路,结构自己整理
[解决办法]
//循环向a函数每次发送200个字节长度(这个是固定的)的buffer,
//a函数中需要将循环传进来的buffer,组成240字节(也是固定的)的新buffer进行处理,
//在处理的时候每次从新buffer中取两个字节打印
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <windows.h>
#include <process.h>
#include <io.h>
//Log{
#define MAXLOGSIZE 20000000
#define MAXLINSIZE 16000
#include <time.h>
#include <sys/timeb.h>
#include <stdarg.h>
char logfilename1[]="MyLog1.log";
char logfilename2[]="MyLog2.log";
static char logstr[MAXLINSIZE+1];
char datestr[16];
char timestr[16];
char mss[4];
CRITICAL_SECTION cs_log;
FILE *flog;
void Lock(CRITICAL_SECTION *l) {
EnterCriticalSection(l);
}
void Unlock(CRITICAL_SECTION *l) {
LeaveCriticalSection(l);
}
void LogV(const char *pszFmt,va_list argp) {
struct tm *now;
struct timeb tb;
if (NULL==pszFmt
[解决办法]
0==pszFmt[0]) return;
_vsnprintf(logstr,MAXLINSIZE,pszFmt,argp);
ftime(&tb);
now=localtime(&tb.time);
sprintf(datestr,"%04d-%02d-%02d",now->tm_year+1900,now->tm_mon+1,now->tm_mday);
sprintf(timestr,"%02d:%02d:%02d",now->tm_hour ,now->tm_min ,now->tm_sec );
sprintf(mss,"%03d",tb.millitm);
printf("%s %s.%s %s",datestr,timestr,mss,logstr);
flog=fopen(logfilename1,"a");
if (NULL!=flog) {
fprintf(flog,"%s %s.%s %s",datestr,timestr,mss,logstr);
if (ftell(flog)>MAXLOGSIZE) {
fclose(flog);
if (rename(logfilename1,logfilename2)) {
remove(logfilename2);
rename(logfilename1,logfilename2);
}
} else {
fclose(flog);
}
}
}
void Log(const char *pszFmt,...) {
va_list argp;
Lock(&cs_log);
va_start(argp,pszFmt);
LogV(pszFmt,argp);
va_end(argp);
Unlock(&cs_log);
}
//Log}
#define ASIZE 200
#define BSIZE 240
#define CSIZE 2
char Abuf[ASIZE];
char Cbuf[CSIZE];
CRITICAL_SECTION cs_HEX ;
CRITICAL_SECTION cs_BBB ;
struct FIFO_BUFFER {
int head;
int tail;
int size;
char data[BSIZE];
} BBB;
int No_Loop=0;
void HexDump(int cn,char *buf,int len) {
int i,j,k;
char binstr[80];
Lock(&cs_HEX);
for (i=0;i<len;i++) {
if (0==(i%16)) {
sprintf(binstr,"%03d %04x -",cn,i);
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
} else if (15==(i%16)) {
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
sprintf(binstr,"%s ",binstr);
for (j=i-15;j<=i;j++) {
sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
}
Log("%s\n",binstr);
} else {
sprintf(binstr,"%s %02x",binstr,(unsigned char)buf[i]);
}
}
if (0!=(i%16)) {
k=16-(i%16);
for (j=0;j<k;j++) {
sprintf(binstr,"%s ",binstr);
}
sprintf(binstr,"%s ",binstr);
k=16-k;
for (j=i-k;j<i;j++) {
sprintf(binstr,"%s%c",binstr,('!'<buf[j]&&buf[j]<='~')?buf[j]:'.');
}
Log("%s\n",binstr);
}
Unlock(&cs_HEX);
}
int GetFromRBuf(int cn,CRITICAL_SECTION *cs,FIFO_BUFFER *fbuf,char *buf,int len) {
int lent,len1,len2;
lent=0;
Lock(cs);
if (fbuf->size>=len) {
lent=len;
if (fbuf->head+lent>BSIZE) {
len1=BSIZE-fbuf->head;
memcpy(buf ,fbuf->data+fbuf->head,len1);
len2=lent-len1;
memcpy(buf+len1,fbuf->data ,len2);
fbuf->head=len2;
} else {
memcpy(buf ,fbuf->data+fbuf->head,lent);
fbuf->head+=lent;
}
fbuf->size-=lent;
}
Unlock(cs);
return lent;
}
void thdB(void *pcn) {
char *recv_buf;
int recv_nbytes;
int cn;
int wc;
int pb;
cn=(int)pcn;
Log("%03d thdB thread begin...\n",cn);
while (1) {
Sleep(10);
recv_buf=(char *)Cbuf;
recv_nbytes=CSIZE;
wc=0;
while (1) {
pb=GetFromRBuf(cn,&cs_BBB,&BBB,recv_buf,recv_nbytes);
if (pb) {
Log("%03d recv %d bytes\n",cn,pb);
HexDump(cn,recv_buf,pb);
Sleep(1);
} else {
Sleep(1000);
}
if (No_Loop) break;//
wc++;
if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
}
if (No_Loop) break;//
}
}
int PutToRBuf(int cn,CRITICAL_SECTION *cs,FIFO_BUFFER *fbuf,char *buf,int len) {
int lent,len1,len2;
Lock(cs);
lent=len;
if (fbuf->size+lent>BSIZE) {
lent=BSIZE-fbuf->size;
}
if (fbuf->tail+lent>BSIZE) {
len1=BSIZE-fbuf->tail;
memcpy(fbuf->data+fbuf->tail,buf ,len1);
len2=lent-len1;
memcpy(fbuf->data ,buf+len1,len2);
fbuf->tail=len2;
} else {
memcpy(fbuf->data+fbuf->tail,buf ,lent);
fbuf->tail+=lent;
}
fbuf->size+=lent;
Unlock(cs);
return lent;
}
void thdA(void *pcn) {
char *send_buf;
int send_nbytes;
int cn;
int wc;
int a;
int pa;
cn=(int)pcn;
Log("%03d thdA thread begin...\n",cn);
a=0;
while (1) {
Sleep(100);
memset(Abuf,a,ASIZE);
a=(a+1)%256;
if (16==a) {No_Loop=1;break;}//去掉这句可以让程序一直循环直到按Ctrl+C或Ctrl+Break或当前目录下存在文件No_Loop
send_buf=(char *)Abuf;
send_nbytes=ASIZE;
Log("%03d sending %d bytes\n",cn,send_nbytes);
HexDump(cn,send_buf,send_nbytes);
wc=0;
while (1) {
pa=PutToRBuf(cn,&cs_BBB,&BBB,send_buf,send_nbytes);
Log("%03d sent %d bytes\n",cn,pa);
HexDump(cn,send_buf,pa);
send_buf+=pa;
send_nbytes-=pa;
if (send_nbytes<=0) break;//
Sleep(1000);
if (No_Loop) break;//
wc++;
if (wc>3600) Log("%03d %d==wc>3600!\n",cn,wc);
}
if (No_Loop) break;//
}
}
int main() {
InitializeCriticalSection(&cs_log );
Log("Start===========================================================\n");
InitializeCriticalSection(&cs_HEX );
InitializeCriticalSection(&cs_BBB );
BBB.head=0;
BBB.tail=0;
BBB.size=0;
_beginthread((void(__cdecl *)(void *))thdA,0,(void *)1);
_beginthread((void(__cdecl *)(void *))thdB,0,(void *)2);
if (!access("No_Loop",0)) {
remove("No_Loop");
if (!access("No_Loop",0)) {
No_Loop=1;
}
}
while (1) {
Sleep(1000);
if (No_Loop) break;//
if (!access("No_Loop",0)) {
No_Loop=1;
}
}
Sleep(3000);
DeleteCriticalSection(&cs_BBB );
DeleteCriticalSection(&cs_HEX );
Log("End=============================================================\n");
DeleteCriticalSection(&cs_log );
return 0;
}
[解决办法]
不需要循环开线程,两个就够了, 线程间不要加同步机制,一个打印生产者,一个打印消费者。就可以实现了,线程在调度时,其实也不是随机的,由于优先级相同,那么就拿时间片调度,会出现1、1、1、2、2、1、2、1、1、2、2。。。。的现象。
[解决办法]
线程创建时就挂起,然后需要启动时,就启动他,其他时候是同步问题,可以记录时间戳,而不是输出到屏幕。
为每个线程维护一个变量或者列表,时间戳。
结束测试时,对各个线程的时间戳排序,即可得到各个线程,执行过程的顺序。
输出到控制台是个费时的操作,可能会改变,线程运行过程;
这个才是赵老师,经常挂到嘴边的,测不准原理,实际是人择原理。
人的参与,会改变事件的运行过程,人择原理。