簡體   English   中英

為什么我的線程不運行?

[英]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 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM