I'm keep getting a segmentation fault from where I create thread and declare some variables in the struct...
Does anyone know why?
dispatch_queue_t *dispatch_queue_create(queue_type_t queueType){
int cores = num_cores();
printf("message-queuecreate1");
dispatch_queue_t *dispatch_queue = (dispatch_queue_t *) malloc(sizeof(dispatch_queue_t));
dispatch_queue->HEAD = NULL;
dispatch_queue->END = NULL;
//create a thread array for dispatcher and worker threads
dispatch_queue_thread_t *threads[cores+1];
threads[cores+1]= (dispatch_queue_thread_t *)malloc(sizeof(dispatch_queue_thread_t));
//create semaphores
sem_t queue_task_semaphore;
sem_t queue_thread_semaphore;
sem_t queue_wait_semaphore;
sem_init(&queue_task_semaphore, 0, 1);
sem_init(&queue_thread_semaphore,0,1);
sem_init(&queue_wait_semaphore,0,1);
dispatch_queue->queue_task_semaphore = queue_task_semaphore;
dispatch_queue->queue_thread_semaphore = queue_thread_semaphore;
dispatch_queue->queue_wait_semaphore = queue_wait_semaphore;
//create dispatcher thread
//segmentation fault #1////////////////
threads[0]->current_task=NULL;
threads[0]->queue=dispatch_queue;
pthread_create(threads[0]->thread, NULL, dispatcher_threadloop, threads[0]);
//////////////////////////////////////
if (queueType == CONCURRENT){
int i = 0;
int thread_id=0;
//create worker thread array if the type of the queue is concurrent
while(i<cores){
//create worker thread
thread_id = i+1;
//segmentation fault #2//////////
threads[i+1]->queue=dispatch_queue;
threads[thread_id]->thread=NULL;
threads[thread_id]->current_task=NULL;
pthread_create(threads[thread_id]->thread, NULL, worker_threadloop, (void *)(long)i);
////////////////////////////////
printf("thread %d is created\n",i);
i++;
}
} else {//do smth}
//segmentation fault# 3////////////////
threads[1]->thread=worker_thread;
threads[1]->queue=dispatch_queue;
threads[1]->current_task=NULL;
//////////////////////////////////////
}
return dispatch_queue;
}
Your code is riddled with problems:
Accessing threads[core + 1] is invalid. Also, you're not allocating memory for the threads[0] ... threads[core].
dispatch_queue_thread_t *threads[cores+1];
threads[cores+1]= ....;
So these will fail:
threads[0]->current_task=NULL; /* See above. */
threads[i+1]->queue=dispatch_queue; /* Again, no memory allocated. */
There could be other problems but I would start by slashing the cores+1 stuff and replacing it with:
for (i = 0; i < cores; i++) {
threads[i] = malloc(sizeof(*threads[i]));
}
Assuming
threads[]->thread
is a pthread_t (and not a pthread_t *)
You need to give the reference:
pthread_create(&threads[thread_id]->thread, NULL, worker_threadloop, (void *)(long)i);
.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 4 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I'm creating two different pthreads via pthread_create() and wait for them to exit by calling pthread_join().
When I run the program, the last output is "Waiting for thread1 to finish...", so it actually stops when trying to join the first thread and then terminates.
When I only create and run one thread and wait for its execution to be finished by using pthread_join(), everything works fine and the output is as expected.
What am I missing here? I already searched the web and figured out that pthread_join() doesn't behave as usual when creating more than one thread. But how do I actually use it in order to wait for finishing the execution of two pthreads?
Here's my code:
typedef struct
{
double speed_in_kmh;
double current_power_in_mega_watts;
} DeLorean;
typedef struct
{
unsigned int* cap_indices;
unsigned int array_length;
} IndexContainer;
typedef struct {
unsigned char* c_string;
unsigned int value;
} FluxCapacitor;
DeLorean* delorean__;
FluxCapacitor** capacitors__;
pthread_mutex_t lock;
// Thread function.
void* assembleDeLorean(void* indices)
{
// Get mutex to lock function and make sure
// that only one thread at a time is using it.
pthread_mutex_lock(&lock);
// Declare "indices" parameter as IndexContainer.
IndexContainer* iC = indices;
double sum = 0;
// Iterate through all given indices in iC
// and add value of iC to sum, if index exists.
for (int i = 0; i < 121; ++i)
{
for (int j = 0; j < iC->array_length; ++j)
{
if (i == iC->cap_indices[j])
{
sum += capacitors__[i]->value;
break;
}
}
}
// Assign computed sum to power of global delorean.
delorean__->current_power_in_mega_watts = sum;
// Release mutex.
pthread_mutex_unlock(&lock);
// Stop thread.
pthread_exit(NULL);
}
int main(void)
{
printf("Main thread \"main()\" was started.\n");
capacitors__ = createFluxCapacitorArray(121);
delorean__ = createDeLorean(0, 0);
IndexContainer* iC_1 = malloc(sizeof(*iC_1));
iC_1->array_length = 21;
iC_1->cap_indices = malloc(21 * sizeof(unsigned int));
IndexContainer* iC_2 = malloc(sizeof(*iC_2));
iC_2->array_length = 100;
iC_2->cap_indices = malloc(100 * sizeof(unsigned int));
// Fill iC_1.
for (int i = 0; i < 21; ++i)
{
iC_1->cap_indices[i] = i;
}
// Fill iC_2.
int k = 0;
for (int i = 21; i < 121; ++i)
{
iC_2->cap_indices[k] = i;
++k;
}
// Declare threads.
pthread_t thread1, thread2;
int rT1, rT2;
// Initialize mutex protecting "assembleDeLorean" function.
pthread_mutex_init(&lock, NULL);
// Create & run first thread.
printf("Creating and running thread1.\n");
rT1 = pthread_create(&thread1, NULL, assembleDeLorean, &iC_1);
if (rT1 != 0)
{
printf("Thread 1 could not be created.\n");
return EXIT_FAILURE;
}
printf("Return value of creation of thread1: %d\n", rT1);
// Create & run second thread.
printf("Creating and running thread2.\n");
rT2 = pthread_create(&thread2, NULL, assembleDeLorean, &iC_2);
if (rT2 != 0)
{
printf("Thread 2 could not be created.\n");
return EXIT_FAILURE;
}
printf("Return value of creation of thread2: %d\n", rT2);
// Wait for threads to finish.
printf("Waiting for thread1 to finish...\n");
if (pthread_join(thread1, NULL))
{
printf("An error occured while joining thread1.\n");
return EXIT_FAILURE;
}
printf("Thread1 finished!");
printf("Waiting for thread2 to finish...\n");
if (pthread_join(thread2, NULL))
{
printf("An error occured while joining thread2.\n");
return EXIT_FAILURE;
}
printf("Thread2 finished!");
return EXIT_SUCCESS;
}
You're passing incorrect arguments to your pthread_create() functions.
rT2 = pthread_create(&thread2, NULL, assembleDeLorean, &iC_2);
rT1 = pthread_create(&thread1, NULL, assembleDeLorean, &iC_1);
should be
rT2 = pthread_create(&thread2, NULL, assembleDeLorean, iC_2);
rT1 = pthread_create(&thread1, NULL, assembleDeLorean, iC_1);
im trying to learn Threads, but i have a issue..
I'am trying to create multiple Threads as defined by ThreadCount and close them all after the work is done.
#define ThreadCount 5
just a short snippet of my main
pthread_t pro;
pthread_t con[ThreadCount];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_create(&pro, &attr, producer, fifo);
for(unsigned int i = 0; i <ThreadCount;++i){
pthread_create (&con[i], NULL, consumer, createhilfsStruct(i,fifo));
}
for(unsigned int i = 0; i <ThreadCount;++i){
pthread_join (con[i], NULL);
}
pthread_join (pro, NULL);
printf("Done");
pthread_exit(NULL);
__
typedef struct{
int threadName;
queue* queue;
}hilfsStruct;
typedef struct {
job* buf[QUEUESIZE];
long head, tail;
int full, empty, currentPages, done;
pthread_mutex_t *mut;
pthread_cond_t *notFull, *notEmpty;
} queue;
hilfsStruct* createhilfsStruct(int threadName, queue* q){
hilfsStruct* h = (hilfsStruct*)malloc (sizeof (hilfsStruct));
h->queue = q;
h->threadName = threadName;
return h;
}
queue *queueInit (void) {
queue *q;
q = (queue *)malloc (sizeof (queue));
if (!q) return (NULL);
q->empty = 1;
q->full = 0;
q->head = 0;
q->tail = 0;
q->currentPages = 0;
q->done = 0;
q->mut = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t));
pthread_mutex_init (q->mut, NULL);
q->notFull = (pthread_cond_t *) malloc (sizeof (pthread_cond_t));
pthread_cond_init (q->notFull, NULL);
q->notEmpty = (pthread_cond_t *) malloc (sizeof (pthread_cond_t));
pthread_cond_init (q->notEmpty, NULL);
return (q);
}
And in my consumer function i have a query to check if fifo->done is true and if its true i use exit(0); to kill the program ==> printf("Done") in the main cant get called [obviously]
If i swap the exit(0) for an pthread_exit(3); // i found this online but i cant figure out why 3
It doesn't exit the thread and the program is just idling and never closes / never reaches anything below the pthread_join
My first try was to use pthread_t con, pro; instead of pthread_t con[..] and just pthread_join(con,NULL) but that wasn't working either.
What am i doing wrong?
Ty guys, and have a nice day
static int res1 = 0;
static int res2 = 0;
static int res3 = 0;
static int counter = 0;
static sem_t sem;
void * func_thread1(void *p)
{
sleep(2);
res1 = 1;
printf("func_thread1\n");
sem_post(&sem);
return NULL;
}
void * func_thread2(void *p)
{
sleep(2);
res2 = 2;
printf("func_thread2\n");
sem_post(&sem);
return NULL;
}
void * func_thread3(void *p)
{
sem_wait(&sem);
sem_wait(&sem);
res3 = res1 + res2;
printf("func_thread3\n");
return NULL;
}
void main()
{
sem_init(&sem, 0, counter);
pthread_t pd1, pd2, pd3;
pthread_create(&pd1, NULL, func_thread1, NULL);
pthread_create(&pd2, NULL, func_thread2, NULL);
pthread_create(&pd3, NULL, func_thread3, NULL);
//pthread_join(pd3, NULL);
printf("main_thread\n");
printf("%d", res3);
}
I'm trying to understand how semaphore works.
I'm trying to make the td3 block to wait for the td1 and the td2.
In my opinion, the sem_wait will block twice. If the sem_posts in func_thread1 and in func_thread2 are executed, func_thread3 could continue.
However, it doesn't work unless I add pthread_join(td3, NULL) in main. I think the join is not necessary because sem_wait can block.
So pthread_join is necessary or I use semaphore incorrectly?
pthread_join is mandatory in your implementation.
Otherwise your process finishes (ie. main returns), and all tasks (ie. threads) are killed before thread 3 prints anything.
I'm doing parallel sorting using pthreads. Currently, I'm working with 4 threads and I have just started out , so right now no threads access same global locations. ( I have declared two variables globally, variables are arrays of large size and I'm making sure no two threads access the same index.)
Inside AASort , I have another function being called. This code works if I don't call any function within the AASort function.
unsigned int Numbers [N/4] [4];
unsigned int vMergedArray[NumProcs][64][4];
unsigned int v[NumProcs][2][4];
main()
{
/* Initialize array of thread structures */
threads = (pthread_t *) malloc(sizeof(pthread_t) * NumProcs);
assert(threads != NULL);
for(threadId=0; threadId < NumProcs; threadId++) {
ret = pthread_create(&threads[threadId], &attr, AASort, (void*) threadId);
assert(ret == 0);
}
for(threadId=0; threadId < NumProcs; threadId++) {
ret = pthread_join(threads[threadId], NULL);
assert(ret == 0);
}
}
I learn threads. I have read that thread terminates after it is out of a function (that is passed as parameter to pthread_create function).
So I create threads in the loop, they are executed and afterwards they are terminated.
(sorry for some long code)
But when I call a function pthread_create, new threads get the same ids. Why?
struct data {
FILE *f;
};
void *read_line_of_file(void *gdata) {
pthread_mutex_lock(&g_count_mutex); // only one thread can work with file,
//doing so we block other threads from accessing it
data *ldata = (data *) gdata;
char line[80];
int ret_val =fscanf(ldata->f,"%s",line);
pthread_mutex_unlock(&g_count_mutex); // allow other threads to access it
if (ret_val != EOF)
printf("%s %lu\n ", line, pthread_self());
// some time consuming operations, while they are being executed by one thread,
// other threads are not influenced by it (if there are executed on different cores)
volatile int a=8;
for (int i=0;i <10000;i++ )
for (int i=0;i <10000;i++ ) {
a=a/7+i;
}
if (ret_val == EOF) // here thread ends
pthread_exit((void *)1);
pthread_exit((void *)0);
}
int main() {
int kNumber_of_threads=3, val=0;
pthread_t threads[kNumber_of_threads];
int ret_val_from_thread=0;
data mydata;
mydata.f = fopen("data.txt","r");
if ( mydata.f == NULL) {
printf("file is not found\n");
return 0;
}
for( ; val != 1 ;) {
// THIS IS THAT PLACE, IDs are the same (according to the number of processes),
// I expected them to be changing..
for(int i=0; i<kNumber_of_threads; i++) {
pthread_create(&threads[i],NULL,read_line_of_file, &mydata);
}
for(int i=0; i<kNumber_of_threads; i++) {
pthread_join(threads[i], (void **) &ret_val_from_thread);
if (ret_val_from_thread != 0)
val = ret_val_from_thread;
}
printf(" next %d\n",val);
}
printf("work is finished\n");
fclose(mydata.f);
return 0;
}
as result, I see that id of threads are not being changed:
I wonder, are new threads really created?
Thanks in advance!
Thread IDs are only guaranteed to be different among currently running threads. If you destroy a thread and create a new one, it may well be created with a previously used thread ID.