gpt4 book ai didi

c++ - 为什么我的线程没有运行?

转载 作者:行者123 更新时间:2023-11-28 07:37:32 25 4
gpt4 key购买 nike

// windows_procon.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <windows.h>
#include <process.h>
using namespace std;

HANDLE mutex;
HANDLE emptySlots;
HANDLE filledSlots;

#define BUFFER_SIZE 10

void *producer(void *);
void *consumer(void *);
int produceItem(void);
void printBuffer(void);

int buffer[BUFFER_SIZE];
int head = 0;
int tail = 0;

int _tmain(int argc, _TCHAR* argv[])
{
DWORD prodThrdID, consThrdID;

mutex = CreateMutex(NULL,FALSE,NULL);
emptySlots = CreateSemaphore(NULL,BUFFER_SIZE,BUFFER_SIZE,NULL);
filledSlots = CreateSemaphore(NULL,0,0,NULL);

srand(time(NULL));

_beginthreadex(NULL, 0, (unsigned int(__stdcall *)(void*))producer,
0, 0, (unsigned int *)&prodThrdID);
_beginthreadex(NULL, 0, (unsigned int(__stdcall *)(void*))consumer,
0, 0, (unsigned int *)&consThrdID);

return 0;
}

void *producer(void *n)
{
int item;
for(int i = 0; i <BUFFER_SIZE+5; i++)
{
WaitForSingleObject(emptySlots,INFINITE);
WaitForSingleObject(mutex,INFINITE);

item = produceItem();
//printf("Producing");

cout << "Producing: " << item << endl;
//logfile << "Producing: "<< item << endl;
//fprintf(logfile, "Producing: %d \n", item);
buffer[head] = item;
head = (head + 1) % BUFFER_SIZE;
printBuffer();

ReleaseMutex(mutex);
ReleaseSemaphore(filledSlots,1, NULL);
}
return n;
}

void *consumer(void *n)
{
for(int i = 0; i <BUFFER_SIZE+5; i++)
{
WaitForSingleObject(filledSlots,INFINITE);
//Sleep(500);
WaitForSingleObject(mutex,INFINITE);

cout << "Consuming: " << buffer[tail] << endl;

buffer[tail] = 0;
tail = (tail + 1) % BUFFER_SIZE;
printBuffer();

ReleaseMutex(mutex);
ReleaseSemaphore(emptySlots,1, NULL);
}
return n;
}

int produceItem(void)
{
int x = (rand()%11 + 1);
return x;
}

void printBuffer(void)
{
for(int i = 0; i <BUFFER_SIZE; i++)
{
printf("%d ", buffer[i]);
}
printf("END \n");
}

我这里的程序应该是生产者-消费者问题的算法。我想我的算法可以纠正我唯一的问题是我无法让线程正常运行。谁能告诉我问题出在哪里?

最佳答案

您需要等待您使用 _beginthreadex 创建的线程完成它们的工作,因为您的程序将在创建它们后立即退出。我没有进一步研究你的逻辑。

这是一个例子。

hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );
WaitForSingleObject( hThread, INFINITE );

关于c++ - 为什么我的线程没有运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16452111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com