Hello,
I would like to ask to my code, when I'm trying inserting to the linked list new nodes through threads, after first insert(by first thread) I've got:
Code:
Segmentation fault (core dumped)
here is my code:
Code:
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
typedef struct list {
int number;
struct list *next;
}LIST;
LIST *a;
void *init()
{
a = (LIST*)malloc(sizeof(LIST));
a->number = -1;
a->next = NULL;
return a;
}
void *insert(int number)
{
LIST *pom;
LIST *new;
new = (LIST*)malloc(sizeof(LIST));
new->number = number;
new->next = NULL;
if(a->number == -1 || a->number>=number)
{
if(a->number == -1)
{
a->number=number;
return a;
}
new->next=a;
a=new;
return;
}
else
{
pom=a;
while(pom->next != NULL && pom->next->number < number)
{
pom=pom->next;
}
new->next=pom->next;
pom->next=new;
}
}
void *delete(int number)
{
LIST *prev=NULL;
LIST *curr;
curr=a;
while(1)
{
if(number == curr->number)
{
if(prev == NULL)
{
a=curr->next;
free(curr);
}
prev->next=curr->next;
free(curr);
}
prev=curr;
curr=curr->next;
}
}
void *thread(void *arg)
{
int *pole;
int i, randCount;
randCount = (int*)arg;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pole = malloc(randCount*sizeof(int));
pthread_t id = pthread_self();
for(i=0; i<randCount; i++)
{
pole[i]=rand() % 20;
pthread_mutex_lock( &mutex1 );
insert(pole[i]);
pthread_mutex_unlock( &mutex1 );
printf("Vlozene: %d by: %d\n", pole[i], id);
}
for(i=0; i<randCount; i++)
{
pthread_mutex_lock( &mutex2 );
delete(pole[i]);
pthread_mutex_unlock( &mutex2 );
printf("Vymazane: %d by: %d\n", pole[i], id);
}
printf("\n");
return NULL;
}
void main(int argc, char** argv)
{
LIST *pom=NULL;
int numbersCount, threadsCount, i;
printf("Zadajte pocet cisiel a pocet vlakien:\n");
scanf("%d %d", &numbersCount, &threadsCount);
int *threadsArray, result;
if(numbersCount < threadsCount)
{
printf("Pocet vlakien je vacsi ako pocet cisiel! Pocet vlakien ");
printf("bude upraveny na hodnotu, ktora sa rovna poctu cisiel.\n");
threadsCount = numbersCount;
}
a = init();
threadsArray = malloc(threadsCount*sizeof(int));
result = numbersCount / threadsCount;
for(i=0; i<threadsCount; i++)
{
threadsArray[i]=result;
}
result = numbersCount % threadsCount;
for(i=0; i<result; i++)
{
threadsArray[i]++;
}
for(i=0; i<threadsCount; i++)
{
printf("%d ",threadsArray[i]);
}
//threading
int err;
pthread_t pth;
for(i=0; i<threadsCount; i++)
{
err = pthread_create(&pth, NULL, &thread, threadsArray[i]);
if(err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
else
printf("\n Thread created successfully\n");
sleep(1);
}
for(i=0; i<threadsCount; i++)
{
pthread_join(pth, NULL);
}
}
when I tried run without threading, insert worked fine.
Thank you