Browse Source

Fixed some bugs involving timing, changed a few variable names and changed the constants' names and values.

Changed ConsProd.c to main.c, refactored Makefile and made a few last minute changes.

Make Windows version

Remove executables and .vs
master
Cameron Weinfurt 2 years ago
committed by stew3254
parent
commit
e0c4287fc6
  1. 86
      Cons_Prod.c
  2. 33
      Makefile
  3. 31
      Producer Consumer.sln
  4. 162
      Producer Consumer.vcxproj
  5. 36
      Producer Consumer.vcxproj.filters
  6. 4
      Producer Consumer.vcxproj.user
  7. 98
      main.c
  8. 2
      thread.c
  9. 4
      thread.h

86
Cons_Prod.c

@ -1,86 +0,0 @@
/***** Global Includes *****/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/***** Local Includes *****/
#include "queue.h"
#include "thread.h"
/***** Constants *****/
#define TIME_TO_PRODUCE 1 // second
#define TIME_TO_CONSUME 1 // second
#define LOOP 10
void producer(queue *q)
{
for (int i = 0; i < LOOP; ++i)
{
/*
* TODO for students: obtain the lock and release the lock somewhere
*/
while (queueIsFull(q));
enqueue(q, i+1);
printf ("producer: produced %d th.\n",i+1);
sleep_microseconds(PRODUCER_SLEEP_S * 1000000);
}
}
void consumer(queue *q)
{
// Simulate consumers' random arrival
sleep_microseconds((rand()%LOOP) * 1000000);
/*
* TODO for students: obtain the lock and release the lock somewhere
*/
while (queueIsFull(q));
sleep_microseconds(CONSUMER_SLEEP_S * 1000000);
printf ("------------------------------------>consumer: recieved %d.\n", dequeue(q));
}
int main()
{
// Initialize the queue. If the queue fails to initialize, kill the program.
queue *fifo = queueInit();
if (fifo == NULL)
{
fprintf(stderr, "main: Queue Init failed.\n");
exit (1);
}
// Seed the random number generator using the system clock.
unsigned int iseed = (unsigned int) time(NULL);
srand(iseed);
// Start one producer thread and as many consumer threads as specified above.
thread_t pro, con[LOOP];
create_thread(&pro, producer, fifo);
for (int i = 0; i < LOOP; ++i)
{
sleep_microseconds((rand() % 2) * 1000);
create_thread(&con[i], consumer, fifo);
}
// Let the producers and consumers finish before cleaning up.
wait_for_threads(&pro, 1);
wait_for_threads(con, LOOP);
// Clean up the queue.
queueDestroy(fifo);
#ifdef WINDOWS
// If this is running in Windows, execute the "pause" shell command so that
// the command prompt window doesn't close after this program finishes.
system("pause");
#endif
return 0;
}

33
Makefile

@ -1,11 +1,30 @@
build: Cons_Prod.c
gcc Cons_Prod.c thread.c queue.c -O2 -DUNIX -pthread -o Cons_Prod
CC = gcc
GLOBAL_FLAGS = -DUNIX -lpthread
debug: Cons_Prod.c
gcc Cons_Prod.c thread.c queue.c -g -DUNIX -pthread -o Cons_Prod
all: build
run: Cons_Prod
./Cons_Prod
build:
FLAGS="-O2"
export FLAGS
$(MAKE) _all
debug:
FLAGS="-g"
export FLAGS
$(MAKE) _all
_all: main.o thread.o queue.o
$(CC) $(FLAGS) $(GLOBAL_FLAGS) main.o thread.o queue.o -o ConsumerProducer
rm *.o
main.o: main.c thread.h queue.h
$(CC) $(FLAGS) $(GLOBAL_FLAGS) -c main.c -o main.o
thread.o: thread.c thread.h queue.h
$(CC) $(FLAGS) $(GLOBAL_FLAGS) -c thread.c -o thread.o
queue.o: queue.c queue.h
$(CC) $(FLAGS) $(GLOBAL_FLAGS) -c queue.c -o queue.o
clean:
rm Cons_Prod
rm ConsumerProducer

31
Producer Consumer.sln

@ -0,0 +1,31 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29728.190
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Producer Consumer", "Producer Consumer.vcxproj", "{C580CBDB-E51B-4027-AEBA-2A4E19F8FB40}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C580CBDB-E51B-4027-AEBA-2A4E19F8FB40}.Debug|x64.ActiveCfg = Debug|x64
{C580CBDB-E51B-4027-AEBA-2A4E19F8FB40}.Debug|x64.Build.0 = Debug|x64
{C580CBDB-E51B-4027-AEBA-2A4E19F8FB40}.Debug|x86.ActiveCfg = Debug|Win32
{C580CBDB-E51B-4027-AEBA-2A4E19F8FB40}.Debug|x86.Build.0 = Debug|Win32
{C580CBDB-E51B-4027-AEBA-2A4E19F8FB40}.Release|x64.ActiveCfg = Release|x64
{C580CBDB-E51B-4027-AEBA-2A4E19F8FB40}.Release|x64.Build.0 = Release|x64
{C580CBDB-E51B-4027-AEBA-2A4E19F8FB40}.Release|x86.ActiveCfg = Release|Win32
{C580CBDB-E51B-4027-AEBA-2A4E19F8FB40}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A9B2D998-7B06-49CA-B812-A66BA8D3A32F}
EndGlobalSection
EndGlobal

162
Producer Consumer.vcxproj

@ -0,0 +1,162 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.c" />
<ClCompile Include="queue.c" />
<ClCompile Include="thread.c" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="queue.h" />
<ClInclude Include="thread.h" />
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>16.0</VCProjectVersion>
<ProjectGuid>{C580CBDB-E51B-4027-AEBA-2A4E19F8FB40}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>ProducerConsumer</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v142</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalOptions>/D WINDOWS %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<PrecompiledHeader>NotUsing</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<AdditionalOptions>/D "WINDOWS" %(AdditionalOptions)</AdditionalOptions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>

36
Producer Consumer.vcxproj.filters

@ -0,0 +1,36 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="queue.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="thread.c">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="main.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="queue.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="thread.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>

4
Producer Consumer.vcxproj.user

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup />
</Project>

98
main.c

@ -0,0 +1,98 @@
/***** Global Includes *****/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/***** Local Includes *****/
#include "queue.h"
#include "thread.h"
/***** Constants *****/
#define TIME_TO_PRODUCE 1000 // milliseconds
#define TIME_TO_CONSUME 1000 // milliseconds
#define LOOP 10
/***** Producer *****
* The function called by the producer thread.
*
* TODO for students: This function does not lock the queue and will
* ultimately race with the consumers. Experiment with locking and unlocking
* the producer using the queueLock() and queueUnlock() functions.
*/
void producer(queue *q)
{
for (int i = 0; i < LOOP; ++i)
{
// Pretend that expensive operations are occuring by sleeping.
sleep_milliseconds(TIME_TO_PRODUCE);
// Busy loop while the queue is full.
while (queueIsFull(q));
// Put the produced item onto the queue and print that the enqueue occured.
enqueue(q, i+1);
printf ("producer: produced %d th.\n",i+1);
}
}
/***** Consumer *****
* The function called by the consumer threads.
*
* TODO for students: The consumers does not lock the queue when consuming
* and ultimately race with the producer and other consumers. Experiment
* with the queueLock() and queueUnlock() functions within this function.
*/
void consumer(queue *q)
{
// Simulate the consumer's random arrival
sleep_milliseconds((rand()%LOOP) * 1000);
// Wait for an item to be in the queue.
while (queueIsEmpty(q));
// Pretend to consume the
sleep_milliseconds(TIME_TO_CONSUME);
printf ("------------------------------------>consumer: recieved %d.\n", dequeue(q));
}
int main()
{
// Initialize the queue. If the queue fails to initialize, kill the program.
queue *q = queueInit();
if (q == NULL)
{
fprintf(stderr, "main: Queue Init failed.\n");
exit (1);
}
// Seed the random number generator using the system clock.
unsigned int iseed = (unsigned int) time(NULL);
srand(iseed);
// Start one producer thread and as many consumer threads as specified above.
thread_t pro, con[LOOP];
create_thread(&pro, producer, q);
for (int i = 0; i < LOOP; ++i)
{
sleep_milliseconds((rand() % 2) * 1000);
create_thread(&con[i], consumer, q);
}
// Let the producers and consumers finish before cleaning up.
wait_for_threads(&pro, 1);
wait_for_threads(con, LOOP);
// Clean up the queue.
queueDestroy(q);
#ifdef WINDOWS
// If this is running in Windows, execute the "pause" shell command so that
// the command prompt window doesn't close after this program finishes.
system("pause");
#endif
return 0;
}

2
thread.c

@ -34,7 +34,7 @@ void wait_for_threads(thread_t *ts, int c)
}
else
{
WaitForMultipleObjects(c, ts, TRUE, INFINITE);
WaitForMultipleObjects(c, ts, true, INFINITE);
}
#endif
}

4
thread.h

@ -8,7 +8,7 @@
#define thread_t pthread_t
#define mutex_t pthread_mutex_t
#define sleep_microseconds(us) usleep(us)
#define sleep_milliseconds(ms) usleep(ms * 1000)
#endif
@ -19,7 +19,7 @@
#define thread_t HANDLE
#define mutex_t HANDLE
#define sleep_microseconds(us) Sleep(us)
#define sleep_milliseconds(ms) Sleep(ms)
#endif

Loading…
Cancel
Save