Pointer incrementing
Apr 18, 2013 at 1:01am Apr 18, 2013 at 1:01am UTC
Hi, I am trying to increment the pointer I send when creating a pthread but it doesn't compile. The increment is at line 30, its written in C. How can I get this to work?
Main:
1 2 3 4 5 6
//create all producers
for (i = 0; i < nproducers; i++)
{
pcount[i] = 0;
pthread_create (&tid_produce[i], NULL, producer, &pcount[i]);
}
Function:
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
void *producer(void *param)
{
buffer_item item;
int i;
while (go == 0)
{
sem_wait(&empty);
sem_wait(&mutex);
//sleep for period of time less than thread max time
sleep( rand() % threadTime );
//generate a random number 1 - 100
item = rand() % 100 + 1;
if (buffer_insert_item(item) != 0)
{
//print buffer stats if user opts in cmd
if ( toupper(printFull[5][0]) == 'Y' )
{
//printf("pindex: %d\n", pindex);
printf("All buffers full. Producer %d waits.\n\n" , (int )pthread_self() );
}
}
else
{
//increment total produced
totProduced++;
(*param)++; /* <---------------- HERE !!!!!!!!!!!!!! */
//print buffer stats if user opts in cmd
if ( toupper(printFull[5][0]) == 'Y' )
{
printf("Producer %d writes %d" , (unsigned int )pthread_self(), item);
printResults();
}
}
//signal the consumer thread
sem_post(&full);
sem_post(&mutex);
}
}
Apr 18, 2013 at 1:09am Apr 18, 2013 at 1:09am UTC
You can't dereference a void pointer. If pcount[i] is an int you have to cast the pointer to an int pointer before dereferencing it. (*(int *) param)++;
Apr 18, 2013 at 1:15am Apr 18, 2013 at 1:15am UTC
When I change it as you suggested and compile I get:
error: invalid type argument of âunary *â
I swapped what you wrote with line 30, is that right?
Apr 18, 2013 at 9:41am Apr 18, 2013 at 9:41am UTC
Yes.
Apr 18, 2013 at 1:15pm Apr 18, 2013 at 1:15pm UTC
That config yields the error I specified above at compile time.
Apr 18, 2013 at 10:12pm Apr 18, 2013 at 10:12pm UTC
I don't know why or how but it compiled, ran, and worked!
Topic archived. No new replies allowed.