posix threads error
Lucas Prado Melo
lucaspm@dcc.ufba.br
Sun Dec 16 22:49:00 GMT 2007
Please forgive me if this is off-topic:
I've written a simple test program with posix threads and a 'glibc'
attempt was detected.
The code:
-----main.c-------
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>
#include "stack.c"
/*
* THREAD EXPERIMENT
*
* There are various threads:
* I, II and main
* thread I repeatly pushes to 'stck' a value (NTIMES times)
* thread II then pop repeatly and show the value (NTIMES-1 times)
* main thread then pushes the last values and quit
*/
#define NTIMES 10000000
#define die(msg) do { perror(msg); exit(1); } while(0)
void * doPush(void * data);
void * doPop(void * data);
struct pack{
Stack stck;
pthread_mutex_t mutex;
};
int main(int argc, char *argv[]){
void *trashbin;
pthread_t peer[2];
struct pack pck;
//initialize pck mutex
if( pthread_mutex_init(&( pck.mutex), NULL) != 0 )
die("pthread_mutex_init");
//and make it multi-threaded
if( pthread_create(&peer[0], NULL, doPush, (void*)&pck) != 0 )
die("pthread_create");
if( pthread_create(&peer[1], NULL, doPop, (void*)&pck) != 0 )
die("pthread_create");
//wait all threads do their stuff
pthread_join(peer[0],&trashbin);
pthread_join(peer[1],&trashbin);
pthread_mutex_lock( &(pck.mutex) );
printf("Last one: %c\n", pop( &(pck.stck) ));
pthread_mutex_unlock( &(pck.mutex) );
//destroy pck mutex
if( pthread_mutex_destroy( &( pck.mutex) ) != 0 )
die("pthread_mutex_destroy");
return 0;
}
void * doPush(void * data){
struct pack * pck = (struct pack *)data;
int x;
for(x=0;x<NTIMES;x++){
int chr;
chr = x%('z'-'a'+1);
chr += 'a';
//try to push the data... using mutex!
pthread_mutex_lock( &(pck->mutex) );
push( &(pck->stck), (void*)chr );
pthread_mutex_unlock( &(pck->mutex) );
}
pthread_exit( NULL );
}
void * doPop(void * data){
struct pack * pck = (struct pack *)data;
int x;
for(x=0;x<(NTIMES-1);x++){
pthread_mutex_lock( &(pck->mutex) );
printf("%c ", pop( &(pck->stck) ) );
pthread_mutex_unlock( &(pck->mutex) );
}
printf("\n");
pthread_exit( NULL );
}
----------------------
-----stack.c-------
#ifndef STACK_C
#define STACK_C 1
#include <stdlib.h>
struct stack {
void * el;
struct stack *next;
};
typedef struct stack * Stack;
void stackInit(Stack * stck){
*stck = NULL;
return;
}
//pushes an element to the stack
void push(Stack * stck, void * el){
struct stack * ne;
ne = malloc(sizeof(struct stack));
ne->el = el;
ne->next = *stck;
*stck = ne;
return;
}
//pops an element from stack
//return NULL if there's no element in the stack
void * pop(Stack * stck){
struct stack * de;
void * el;
de = *stck;
*stck = (*stck)->next;
if(de != NULL ){
el = de->el;
free(de);
}
else
el = NULL;
return el;
}
#endif
----------------------
Why does it happen?
More information about the Gcc-help
mailing list