为什么我的线程没有运行?
Why aren't my threads running?
// 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 );
相关文章:
- system() 无法运行我的程序,因为空间
- 运行我的代码时出现分段错误(核心转储)问题
- 正在尝试循环回到开始以再次运行我的程序
- arm_data在第二次运行我的程序时中止失败,然后
- 我想在终端窗口中运行我的 CLion 程序
- 如何在关闭Qt控制台应用程序之前运行我的析构函数?
- 使用 dev-c++ 运行我的 GIS 应用程序可以"gdal201.dll is missing"
- 当我运行我的程序时,即使"user"输入数字||C++ 绘画作业
- Inno设置编译器未运行我的C/C 代码
- 在代码块中运行我的第一个图形程序
- 正在重新运行我的主方法
- 如何在MacOS上使用根特权运行我的应用程序
- C++ Xcode 不会运行我的 for 循环(很短)
- STLPORT.5.2.dll 和视觉C++之间有什么关系?我是否需要 stlport 才能运行我的程序
- 无法通过循环运行我的代码,但是手动复制和粘贴有效
- 运行我的SFML脚本的问题
- 在Visual Studio 2012中运行我的OpenCV代码时无法找出'u202A'警告
- dev为什么dev-C++不运行我的程序
- 每当我尝试在codelite中运行我的项目时,任何更改我'We让人觉得被忽视了
- 在旧版本的linux上运行我的代码