Question about semaphores

dont want any code but could someone point to me where it is I'm going wrong. keeps saying undefined reference to signal. Am i supposed to write my own def for it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

typedef int buffer_item;
#define BUFFER_SIZE 5
#define SLEEP_TIME 5
#define TRUE 1
#ifdef RAND_MAX		//only generate #s between 1 & 20
#undef RAND_MAX
#define RAND_MAX [20]
#endif

buffer_item buffer[BUFFER_SIZE];
pthread_mutex_t mutex;
sem_t empty;
sem_t full;

buffer_item item;		//variable to hold randomly generated # to store in buffer[]
int count=0;

int insert_item(buffer_item item)
{
	if(count<BUFFER_SIZE){
		buffer[count]=item;
		count++;
	}
	return 0;
}

int remove_item(buffer_item *item)
{
	if(count>=0){
		item=buffer[count];
		count--;
	}
	return 0;
}


void *producer(void *param)
{
	int return_result1;		//holds the return value of insert_item for error check
	do{
		int rand_sleep_time=((rand()/2)+5);
		item=rand();
		sleep(rand_sleep_time);
		sem_wait(&empty);
		pthread_mutex_lock(&mutex);
		return_result1=insert_item(item);
		printf("Producer generated random integer: %d and stored it at index: %d/n",item,(count-1));
		pthread_mutex_unlock(&mutex);
		sem_signal(&full);
	}while(TRUE);
}

void *consumer(void *param)
{
	int return_result2;		//holds the return value of remove_item for error check
	buffer_item* ptr=&item;
	do{
		int rand_sleep_time=((rand()/2)+5);
		sleep(rand_sleep_time);
		sem_wait(&full);
		pthread_mutex_lock(&mutex);
		return_result2=remove_item(ptr);
		printf("Consumer consumed random integer: %d stored at index: %d/n",&data,(count+1));
		pthread_mutex_unlock(&mutex);
		sem_signal(&empty);
	}while(TRUE);
}

int main(int argc, char *argv[])
{
	int sleepTime;

	if(argc != 2)
	{
		fprintf(stderr, "Useage: <sleep time> \n");
		return -1;
	}

	sleepTime = atoi(argv[1]);

	//Initizlize the rounded array 
	for(int i=0; i<BUFFER_SIZE; i++)
		buffer[i] = -1;

	//Initialize the the locks
	pthread_mutex_init(&mutex, NULL);
	sem_init(&empty, 0, BUFFER_SIZE);
	sem_init(&full, 0, 0);
	srand(time(0));

	//Create the producer and consumer threads
	pthread_t tid;
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_create(&tid, &attr, producer, NULL);

	pthread_create(&tid, &attr, consumer, NULL);

	//Sleep for user specified time
	sleep(sleepTime);
	return 0;
}
}
Last edited on
Topic archived. No new replies allowed.