Hello,
I am trying a multithreaded code but I am recieving sigtrap. I am trying to test a round robin algorithm but somehow I am SIGTRAPing in the atomic_push function.
Code:
typedef struct _s
{
char system[32];
struct _s* next;
} node;
static node* s_head = 0;
static pthread_mutex_t mutex;
static void atomic_push(node** pHeader, const char* data)
{
pthread_mutex_init(&mutex, NULL);
pthread_mutex_lock(&mutex);
critical_section:
{
node* pnode = (node*) malloc(sizeof(node));
strcpy(pnode->system, data);
pnode->next = (*pHeader);
(*pHeader) = pnode;
}
pthread_mutex_unlock(&mutex);
}
static const char* systems[4] =
{
{"system1"},
{"system2"},
{"system3"},
{"system4"}
};
static int fetch_and_add(int* pVar, int value)
{
asm volatile ("lock; xaddl %%eax, %2;"
:"=a"(value)
:"a" (value), "m" (*pVar)
:"memory");
return value;
}
static int atomic_int = 1;
static void run(void)
{
char* str = systems[fetch_and_add(&atomic_int, 1) % 4];
atomic_push(&s_head, str);
}
int main(void)
{
int i = 0;
pthread_t tids[500];
for(i=0; i < 500; i++) {
pthread_create(&tids[i],0, &run, 0);
usleep(200);
}
node* it = &s_head;
i =0;
while ( it != NULL ) {
printf("[%d]:[%s]\n", i++, it->system);
it = it->next;
}
return 0;
}
A help will be appreciated.