FAQ Database Discussion Community


Segmentation Fault after pthread_create()

c,segmentation-fault,pthreads
Creating a thread with this: pthread_t thread; pthread_create(&thread, NULL, (void*)&serve_connection, (void*)sockfd); The function I am calling is defined as: void serve_connection (void* sockfd) { ssize_t n, result; char line[MAXLINE]; connection_t conn; connection_init (&conn); conn.sockfd = *((int*)sockfd); while (! shutting_down) { ... ... }} The rest of the function is in...

Is my function thread-safe and reentrant?

c++,multithreading,pthreads
I have a function that is called by two threads each having a local copy of a vector. My Assumption was that since each thread has a different vector the function below is thread-safe. Is the below function thread-safe and reentrant? int Partition(int high, int low, int pivot, std::vector<int>& arr)...

Pthread id and sleep

c,multithreading,pthreads
I need to do the following: Create a thread that creates 10 threads in a row. Each thread just prints it's ID and sleeps for n seconds, where n is the serial number of current thread. But, I can't get passing arguments right, when I run my code it seems...

What is the meaning of “statically allocated”?

c,pthreads
http://linux.die.net/man/3/pthread_mutex_init In cases where default mutex attributes are appropriate, the macro PTHREAD_MUTEX_INITIALIZER can be used to initialize mutexes that are statically allocated. The effect shall be equivalent to dynamic initialization by a call to pthread_mutex_init() with parameter attr specified as NULL, except that no error checks are performed. I know...

c++ issue passing information to pthreads

c++,pthreads,corruption
The issue I am having is that printf debug statements in showData() will give me nonsensical numbers. i.e.: the thread_id is -1781505888. If I insert the printf statements in createThreads() right after I set the values of thread_id, startIndex, and stopIndex then the values will print correctly. Somehow data is...

C - Waiting For Multiple Threads to Terminate

c,multithreading,pthreads,terminate
I am trying to wait for all the threads to terminate before the main() process terminates. Here is what I have so far: void* mapperFunction() { printf("Hello\n"); return NULL; } int main() { int i; // Used in "for" loops. int N = 3; pthread_t* mapperThreads = (pthread_t*) malloc(sizeof(pthread_t) *...

A strange result in a simple pthread code

c,multithreading,pthreads
I wrote the following code: #include <pthread.h> #include <stdio.h> void* sayHello (void *x){ printf ("Hello, this is %d\n", (int)pthread_self()); return NULL; } int main (){ pthread_t thread; pthread_create (&thread, NULL, &sayHello, NULL); printf("HERE\n"); return 0; } After compiling and running I saw 3 different types of outputs. Only "Here" was...

Pthreads and signals C++

c++,pthreads,signals
I'm new to threads and seem to be having a timing problem. When I run my code my output is... Data received! Data processed! and then it just hangs. I assume I'm using wait and signal incorrectly. Help would be greatly appreciated. #include <string.h> #include <pthread.h> #include <stdio.h> #include <unistd.h>...

Blocking in pthread_join()

c,multithreading,unix,pthreads
According to the manual page: The pthread_join() function shall suspend execution of the calling thread until the target thread terminates, unless the target thread has already terminated. So, as I understand, the calling process will block until the specified thread exit. Now consider the following code: pthread_t thrs[NUMTHREADS]; for (int...

C++ Pthread/SFML Music - Error AL lib: (EE) alc_cleanup: 1 device not closed

c++,pthreads,sfml
I have a project that is to recode the Bomberman and I implemented the sf :: Music for music added to main menu but I come across an error: AL lib: (EE) alc_cleanup: 1 device not closed And it's relied to this : void *pthreadSound(void *); int main(int, char **){...

PHP - Multithread a function with pthreads

php,multithreading,pthreads
I'm currently working with pthreads to implement multithreading on a very demanding function. So far I got this working: class Operation extends Thread { public function __construct($arg) { $this->arg = $arg; } public function run() { if ($this->arg) { $parameters = $this->arg; echo my_function($parameters[0],$parameters[1]); } } } $stack = array();...

What are the possible threats that a waiting pthread_mutex might encounter?

multithreading,pthreads
If a pthread is locking a shared resource. Is there any threat that a waiting pthread_mutex might encounter? Something like limitation of parallel pthreads, time limit, event, ... ...

PHP thread - run method not being called

php,pthreads
For some reason my run method is not being called? Any ideas where i'm going wrong? <?php class WorkerThread extends Thread { private $i = 0; public function __construct( $i ) { $this->i = $i; } public function run() { $a = 0; while( $a < 100 ) { file_put_contents(...

Necessity of pthread mutex

c,multithreading,pthreads,mutex
I have an int array[100] and I want 5 threads to calculate the sum of all array elements. Each thread iterates through 20 elements within its dedicated range and writes the sum into a global sum variable. Is a mutex necessary here? There is no synchronization needed since all threads...

C Pthreads numbers

c,multithreading,pthreads
i'm new with C pthreads, and i'm having some little problems on it. I would like to make a program that stops when my var result = 13. I have two threads that add or subtract a randomic number to my result. The problem is that, in the compilated case,...

How can i call an other function from static Thread entry point function in c++?

c++,qt,pthreads
I have in my code a thread and an entry point function like this: static void *readerThreadEntryPoint(void *arg) void *MainWindow::readerThreadEntryPoint(void *arg) { MODES_NOTUSED(arg); } and i want to call a function with this code QBytearray data = socket->ReadAll(); how can i do ? i have an error: invalid use of...

GNU/Linux thread implementation

c,linux,pthreads
Recently, I've read in the "Advanced Linux Programming" book (http://www.advancedlinuxprogramming.com/alp-folder/alp-ch04-threads.pdf, Chapter 4.5) that on GNU/Linux POSIX threads are implemented as processes and that there is some kind of "manager thread" which does some control work. When I run the following example from this book: #include <stdio.h> #include <pthread.h> void* thread_func(void...

Reading from a file in different threads in C

c,multithreading,pthreads
I have a multithreaded server program where each thread is required to read the contents of a file to retrieve data requested by the client. I am using pthreads in C to accomplish creating a thread and passing the function the thread which the thread will execute. In the function,...

Passing in arguments to pthread results in duplicates C

c,multithreading,file-io,pthreads
For an assignment I'm supposed to use pthread to create a multithreaded version of grep called search (that is recursive), where the arguments are ./search pattern ~/dir ~/dir2 ~/dir3.. etc. Also the assignment specifically states that I am supposed to use pthread_exit(NULL) at the end to join all the threads...

Thread blocking on sem_wait causes other threads to hang

c,multithreading,pthreads,semaphore,fifo
I wrote a generic queue in C which is to be used for a variety of payload types. It is a blocking queue so that consumer threads will block waiting for the queue to be populated by producer threads. I have tested the queue code in isolation using check, including...

C++ segmentation fault when creating pthreads

c++,segmentation-fault,pthreads
void createThreads(int k){ struct threadData threadData[k]; int numThreads = k; int i = 0; int err = 0; pthread_t *threads = static_cast<pthread_t*>(malloc(sizeof(pthread_t) * numThreads)); for(i = 0;i<numThreads;i++){ threadData[i].thread_id = i; threadData[i].startIndex = ((N/k)*i); threadData[i].stopIndex = ((N/k)*(i+1)); err = pthread_create(&threads[i], NULL, foo, (void *)&threadData[i]); if(err != 0){ printf("error creating thread\n"); }...

Calculate the sum of two numbers using thread

c,unix,segmentation-fault,pthreads
I have this little program I wrote to read two numbers from a user and calculate their sum using a thread function, which is also responsible for displaying the result on the screen. int global[2]; void *sum_thread(void *arg) { int *args_array; args_array = *(int**)arg; int n1,n2,sum; n1=args_array[0]; n2=args_array[1]; sum =...

Two-Lock Concurrent Queue Algorithm implementation issue

c,multithreading,algorithm,pthreads,concurrent-programming
I was going through the paper of Michael and Scott for Non-Blocking Concurrent Queue Algorithm and Two-Lock Concurrent Queue Algorithm. They have mentioned in the paper that C code for the tested algorithms can be ob- tained from ftp://ftp.cs.rochester.edu/pub/ packages/sched conscious synch/concurrent queues. But since the paper is very old...

Pthread join segmentation fault

c,multithreading,pthreads
I have the following code where two arrays are modified differently (in one case each element is incremented by 1, and in the other each element is decremented by 1) by two threads. It gives segmentation fault. Could you please point out the error? #include <stdio.h> #include <pthread.h> #include <stdlib.h>...

Issue creating multiple threads with pthreads

c,linux,multithreading,ubuntu,pthreads
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <math.h> void *compute() { float total; int i; float oldtotal =0, result =0; for(i=0;i<1999999999;i++) { result =sqrt(1001.0)*sqrt(1001.0); } printf ("Result is %f\n", result); oldtotal = total; total = oldtotal + result; printf("Total is %f\n",total); return NULL; } int main() { pthread_t thread1, thread2;...

interaction between Queue and pool of Threads?

c++,multithreading,pthreads,threadpool
I am creating a C++ application that receives data from an external provider. The amount of data per second can be very big. I have thought of using a thread that pushes the data into a Queue. then a pool of threads will fetch data from that Queue. my questions...

Binding multiple pthreads, each to the same member function of a different object from the same class

pthreads,member-function
I have bound multiple pthreads to independent member function of independent objects from the same class. I had to use of a static member function as a helper since it is not possible to bind a member function directly to a pthread in C++; however, my application behaves strangely and...

phread_cond_broadcast race condition

multithreading,pthreads
I can't find a way to stop this race condition. The main thread calls the broadcast routine to wake up all the threads then calls a cond_wait to wait for all the threads to finish. The last thread to finish signals the main thread. The problem is sometimes not all...

Force unlock a mutex that was locked by a different thread

c,multithreading,pthreads,freebsd
Consider the following test program: #include <stdio.h> #include <string.h> #include <errno.h> #include <strings.h> #include <unistd.h> #include <signal.h> #include <pthread.h> pthread_mutex_t mutex; pthread_mutexattr_t mattr; pthread_t thread1; pthread_t thread2; pthread_t thread3; void mutex_force_unlock(pthread_mutex_t *mutex, pthread_mutexattr_t *mattr) { int e; e = pthread_mutex_destroy(mutex); printf("mfu: %s\n", strerror(e)); e = pthread_mutex_init(mutex, mattr); printf("mfu: %s\n",...

Some pthread code…why is it running slow?

c,pthreads
This code is supposed to coordinate people in a conference. Can anyone help me find out why its so slow? Thanks. It is written in C and uses POSIX threads. This is a mulch-threaded program that helps synchronize a speaker and a hoard of talkative reporters. #include<stdio.h> #include<stdlib.h> #include<pthread.h> typedef...

SIGSEGV when calling Java method from native pthread

java,c,multithreading,jni,pthreads
In a Java project that uses C code via JNI I have a piece of native C code that obtains references to an object and one of its methods, then starts a native thread, passing these references to it in a struct. When the thread tries to call the method,...

luajit/physicsfs mutex deadlock

lua,pthreads,mutex,deadlock,luajit
I've got the following code: local M=ffi.load "physfs" ffi.cdef [[ //basically the preprocessed content of physfs.h, see http://icculus.org/physfs/docs/html/physfs_8h.html ]] M.PHYSFS_init(arg[0]) M.PHYSFS_setSaneConfig("a","b","zip",0,0) function file2str(path) local cpath=ffi.cast("const char *",path) print(1) --debug if M.PHYSFS_exists(cpath)==0 then return nil,"file not found" end print(2) --debug -- some more magic end assert(file2str("someFile.txt")) when calling, I expect debug...

How to Detect a Spurious Wakeup

java,linux,multithreading,pthreads,posix
I have read many posts on this. This answer http://stackoverflow.com/a/6701060/2359945 claimed a 100 bounty by suggesting to test the interrupted flag. I tested this, and it does not work for me. So, the question remains, how do I detect a spurious wakeup, or is it not possible? Thank you. class...

freopen() on OSX 10.10.3

osx,pthreads,io-redirection
I have a C program which spawns a pthread to act as an interactive terminal: reading lines from stdin & acting upon them. The program acts as a kind of shell, fork-ing off processes; each process so created has its stdin re-directed using a call to freopen() before using exec...

Interruption in a linux multithreaded app generate SIGSEGV

c++,c++11,pthreads,signals
I have a x86_64 multithreaded application where I try to emulate avr interrupts: when interrupt occurs application and all threads are suspended while interrupt handler execute defined actions. I thought signals were the solution to do this so I'm trying to catch SIGUSR1 signal, but when I raise SIGUSR1 program...

After signaling a waiting condition variable, when the thread will acquire the lock? What determines it?

c++,pthreads,condition-variable
After searching on the web, and reading the question answers on the stackoverflow, i couldn't find the answer of my question. The wait is called in thread B, and it unlocks the mutex, allowing others access to the condition variable (for signalling). Then, when the condition variable is signalled in...

More threads executed than created

c,linux,multithreading,pthreads
I'm studying thread programming. While doing below example, I got undefined behavior. static void* print_thread_attr (void* param) { pthread_attr_t attr; int detach_state = PTHREAD_CREATE_JOINABLE; pthread_getattr_np (pthread_self(), &attr); pthread_attr_getdetachstate (&attr, &detach_state); pthread_attr_destroy (&attr); printf("Detach state of thread [%u] pid [%d] is %s\n", pthread_self(), getpid(), (PTHREAD_CREATE_JOINABLE == detach_state)? "JOINABLE THREAD":"DETACHED THREAD"); return...

PHP pthreads, in pool tasks, ob_flush and flush cause crash

php,apache,pthreads,threadpool,flush
$p = new Pool(10); for ($i = 0; i<1000; i++){ $tasks[i] = new workerThread($i); } foreach ($tasks as $task) { $p->submit($task); } // shutdown will wait for current queue to be completed $p->shutdown(); // garbage collection check / read results $p->collect(function($checkingTask){ return ($checkingTask->isGarbage); }); class workerThread extends Collectable {...

Passing arguments to a thread

c,pthreads
I have this struct: #define NUM_T 5 typedef struct { int j; int vetor[BUFFER_SIZE]; } estrutura_main; which I want to pass as argument to threads: estrutura_main structure; for(i=0;i<NUM_T;i++){ structure.j=i; pthread_create(&threads[i], NULL, sum,(void*)&structure); } my problem is that when i access j in function sum it is always 4, and it...

Unix c program to calculate pi using threads

c,unix,pthreads
Been working on this assignment for class. Put this code together but its giving me several errors I'm not able to solve. Code #include <stdio.h> #include <stdlib.h> #include <pthread.h> //global variables int N, T; double vsum[T]; //pie function void* pie_runner(void* arg) { double *limit_ptr = (double*) arg; double j =...

Mutex assertion error with non-zero heap

c,pthreads,mutex,heap-memory,memset
If I allocate memory, free it and then try to allocate a mutex and lock it, I get the message Assertion 'mutex->__data.__owner == 0'. I am not an expert in concurrency or low-level programming but this seems odd to me. Code #include <stdlib.h> #include <string.h> #include <pthread.h> void nonzero_heap(){ void...

No prints from the second thread - pthreads with mutex locks

c,multithreading,pthreads
I wrote: #include <pthread.h> #include <stdio.h> #include <sys/types.h> pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int globalVarX; void *threadFunction (void *arg) { pthread_mutex_lock (&mutex1); while (globalVarX < 1000) { printf("x increment by thread id: %d", gettid ()); ++globalVarX; } pthread_mutex_unlock (&mutex1); return NULL; } int main() { pthread_t threadA; pthread_t threadB; if (pthread_create...

How to send message (in C) from one thread to another?

c,multithreading,unix,pthreads
I'm trying to send a message from one thread to another. Each thread knows the thread ID of the other. How can I send a message between them? I've already seen some proposed solutions (message queue, anonymous pipe, etc.) but honestly I didn't get them to work. Obviously I didn't...

pthread_barrier_wait hangs after creation of all threads

multithreading,pthreads,barrier
I'm trying to write a simple program to use a barrier to wait for the creation of several threads before printing a message from the main. Here's my code: #include <iostream> #include <pthread.h> #include <stdio.h> #include <cstdlib> #include <cstdint> #define NUM_THREADS 8 pthread_barrier_t barrier; void *threadFun(void *tid) { intptr_t temp...

Whats the best way to asynchronously return a result (as a struct) that hasn't been fully “set up” (or processed) yet

c,asynchronous,concurrency,pthreads,threadpool
Alright, I honestly have tried looking up "Asynchronous Functions in C" (Results are for C# exclusively), but I get nothing for C. So I'm going to ask it here, but if there are better, already asked questions on StackExchange or what-have-you, please direct me to them. So I'm teaching myself...

Can't synchronize more than 2 threads with pthread_mutex_lock

c,pthreads,mutex
So I'm doing homework for my C class and I came across a problem. I want to sync the acess to my global array with pthread_mutex_lock() but it seems that when 2 or more threads try to lock at the same time it just bugs. Here's my code: #include <stdio.h>...

Why is the segmentation Fault error occuring

c,pthreads
I am getting error Segmentation fault (core dumped) i have narrowed it done to these lines in function threadx while (colatz_nums[j] != 1) {j++; if ((m % 2)==0) { colatz_nums[j] = m/2;} else {colatz_nums[j] = 3 * m +1;} } if I remove these lines I do not get the...

Why are these pthreads segmentation faults possible?

php,multithreading,reference,segmentation-fault,pthreads
In this introduction to pthreads I read that: When the programmer calls Thread::start, a new thread is created, a PHP interpreter context is initialized and then (safely) manipulated to mirror the context that made the call to ::start. And later in the text the segmentation fault problem is addressed. This...

pthread_mutex_errorcheck_np initialization error

c,pthreads,mutex
Below code gives me compilation error: #include<pthread.h> #include<stdio.h> pthread_mutex_t mutex= PTHREAD_MUTEX_ERRORCHECK_NP; int i=0; void *func(void *a) { pthread_mutex_lock(&mutex); i++; printf("The value of thread is: %d\n",i); pthread_mutex_unlock(&mutex); pthread_exit(NULL); } int main() { pthread_t id1,id2; if(pthread_create(&id1,NULL,func,NULL)<0) perror("pthread_create error\n"); pthread_join(id1,NULL); pthread_join(id2,NULL); } The error is: error: invalid initializer pthread_mutex_t mutex=...

C - Timer logic for error condition

c,timer,pthreads,delay,multitasking
I'm working on a project where I have to deal with several sensors, and print out error values to a textfile. Currently I'm doing random generators, to just generate some dummy values. The thing here is that the same errors are stored into the textfile, since the code is running...

Assure the execution of every thread

c,multithreading,pthreads,posix,pthread-join
I want to run 4 different threads calling the same method, and I want to make sure that every single run comes from a different running thread. With the code provided bellow, the method function is ran the expected number of times but it is always done by the same...

Why this simple program on shared variable does not scale? (no lock)

multithreading,concurrency,pthreads,concurrent-programming,pthread-join
I'm new to concurrent programming. I implement a CPU intensive work and measure how much speedup I could gain. However, I cannot get any speedup as I increase #threads. The program does the following task: There's a shared counter to count from 1 to 1000001. Each thread does the following...

Multi-threaded C program much slow in OS X than Linux

c,linux,multithreading,osx,pthreads
I wrote this for an OS class assignment that I've already completed and handed in. I posted this question yesterday, but due to "Academic Honesty" regulations I took it off until after the submission deadline. The object was to learn how to use critical sections. There is a data array...

How to avoid code bloat when using pthreads in C?

c,multithreading,pthreads,c-preprocessor
When writing threaded code in C, I first have to create some struct which includes all the arguments and a wrapper function. This leads to lots of code bloat and is not easy to read. See: struct some_function_args { int arg1; int arg2; int arg3; }; void some_function_wrapper(struct some_function_args* args)...

Multiple arguments to function called by pthread_create() - argument is function pointer

c++,pthreads,function-pointers,argument-passing
My case is similar to another Question. I would like to pass a function as argument and an integer value. Testing the case with a simplfied construction: void print (int x, int y) { cout << "x = " << x << ", y = " << y << endl;...

Sending a glib signal across threads

c++,multithreading,pthreads,signals,glib
I have a thread created using pthreads that I am receiving progress notification callbacks in that thread. This is done in an external non-glib library. I want the callback to emit a glib signal event, but am not sure how to get the event onto the main (GUI) thread. The...

Initialise thread pool

c,multithreading,pthreads
As part of a HW assignment, I'm about to implement a thread pool in ANSI C using pthreads. I'm having difficulty understanding how to initialise my thread pool. I think the idea is to initialise the pool with thread which sleeps until they get a job to do, however I'm...

pthred_exit return variable static vs global scope

pthreads,static-variables,pthread-join
I am seeing different behaviors when variable used to get return values using pthread_join is defined gloabal vs static scope. I have included code_snippet here. Static variables int main() { static int r1,r2; pthread_t t1, t2; int i1[] = {1,2}; int i2[] = {3,4}; r1 = pthread_create( &t1, NULL, myfn,...

Thread synchronisation for C++ map

c++,multithreading,dictionary,pthreads
I'm creating a multithreaded c++ program using pthread (c++98 standard). I have a std::map that multiple threads will access. The access will be adding and removing elements, using find, and also accessing elements using the [] operator. I understand that reading using the [] operator, or even modifying the elements...

Test for std::thread native handle implementation

multithreading,c++11,pthreads,native,handle
With std::thread::native_handle(), I can get the underlying pthreads handle in my implementation (mingw-w64 with pthreads) But is there a way to check during preprocessing if the implementation is actually using native pthreads or something else (win32 threads, etc...) ? I would like to make a code as portable as possible,...

Slow pthreads, does not appear to be mere overhead

c,multithreading,performance,pthreads
I've been trying to figure out why my program that approximates pi with Monte Carlo integration is running much slower with pthreads then single threaded both written in C. I have tested this on two different machines, both running the same OS but different hardware, and the results are almost...

Applying two or more mutexes to a section of code

c++,pthreads,mutex,deadlock
I'm studying mutexes and deadlocks in c++ pthreads from http://www.yolinux.com/TUTORIALS/LinuxTutorialPosixThreads.html I understood them but i stacked at a point. I didn't understand what is the problem of the below code. Can you explain it with simple and clear words please? I quoted from this site: Mutex Deadlock: ... Be careful...

need to know how to interrupt all pthreads

multithreading,pthreads,signals
In Linux, I am emulating an embedded system that has one thread that gets messages delivered to the outside world. If some thread detects an insurmountable problem, my goal is to stop all the other threads in their tracks (leaving useful stack traces) and allow only the message delivery thread...

creating threads using pthread.c

c,multithreading,pthreads,semaphore
I am trying to learn how to create threads in c using the pthread library, I am using the following code: #include <stdlib.h> #include <stdio.h> #include <semaphore.h> #include <pthread.h> static int glob = 0; static sem_t sem; static void *threadFunc(void *arg) { int loops = *((int *) arg); int loc,...

Retrieve pthread_create's arg from outside the thread?

multithreading,pthreads
This is related to How to assign unique ids to threads in a pthread wrapper? and The need for id_callback when in a multithread environment?. When we need to differentiate among unique threads, we cannot use functions like pthread_self because thread ids are reused. In those problems, it was suggested...

Interrupt a accept() that is waiting, just changing a global variable value

c,sockets,pthreads,signals
I'm doing a project for university, a chat system with a server and multiple clients. In the specification document there is written: The main thread does a controlled loop on the global var go, and at each cycle waits for a connection request by an user And also: Server stops...

Mutex or not to Mutex?

pthreads,mutex
I have an array A of length 1024 and I have 4 threads, the first will work on indexes 0 to 255, the second on 256 to 511, the third on 512 to 767, the last will work on indexes 768 to 1023. Do I need a Mutex for that...

Thread creation inside constructor

c++,multithreading,static,pthreads
So, I am using C++11 and I made a class Class C { private: queue<std::int> s; pthread_t x; public: C() {phthread_create(&x, NULL, d_q, NULL); void log(int p); // pushes into q. void* d_q(void* q); // this is a function which will pop s. assume s is thread safe. } The...

Understanding parallel thread execution

c,multithreading,pthreads
Writing simple C code, trying to control output from two different threads: #include <pthread.h> #include <semaphore.h> #include <stdio.h> sem_t sem; void* thread_func(void* aArgs) { printf("Entering thread %p with %d\n", (void*)pthread_self(), (int)aArgs); int i = 0; for(;i < 10; i++) { sem_wait(&sem); if ((i % 2) == (int)aArgs) printf("val is %d...

Linux pthread Producers and Consumers

c,multithreading,concurrency,pthreads,producer-consumer
I have to write a POSIX threads and semaphores based implementation of Producers and Consumers Problem for academical purposes. To check if the implementation is valid I sum all the 'goods' which are produced and all which are consumed. The problem is that second sums vary between subsequent executions of...

Can I call pthread_join on a pthread_detached thread?

c,pthreads
I have 16 threads that spawned from one parent thread. I'm waiting for the children to finish execution by calling pthread_join in the parent. However, afterwards in each of the children threads I call pthread_detach. I'm wondering if the parent will still wait for the children to finish executing. In...

Understanding posix barrier mechanism

c,multithreading,pthreads,posix
Here is piece (very simplified, with global var's and other "smells") of C code, which uses posix barrier primitive to sincronize thread start. #include <pthread.h> #include <stdio.h> pthread_barrier_t barrier; void* thread_func(void* aArgs) { pthread_barrier_wait(&barrier); printf("Entering thread %p\n", (void*)pthread_self()); int i; for(i = 0 ; i < 5; i++) printf("val is...

mmap() and pthreads - copy VMA

c,linux-kernel,pthreads,mmap
I mmap() an anonymous VMA. How do pthreads handle that VMA? I want that the vma with its memory is copied for every thread. Which flags do I need for that purpose?

waitpid for child process not succeeding

c,linux,process,pthreads,waitpid
I am starting a process using execv and letting it write to a file. I start a thread simultaneously that monitors the file so that it's size does not exceed a certain limit using stat.st_size. Now, when the limit is hit, I waitpid for the child process, but this throws...

C++ erroring creating n pthreads-

c++,compiler-errors,pthreads
Getting the following errors in a function that should take an int k and create k pthreads: cse451.cpp:95:60: error: invalid conversion from ‘void*’ to ‘pthread_t* {aka long unsigned int*}’ [-fpermissive] cse451.cpp:97:54: error: invalid use of void expression I have a feeling it has to do with the foo() function (which...

What if a condition variable signals to a locked thread?

c,multithreading,pthreads,mutex,condition-variable
In the (pseudo-)code below, cond might wake up while it shouldn't, for whatever reason. So I put a while loop there. When it does wake up, it will still consume the lock, so it is guaranteed that in out() only one thread is doing its job. But what happens if,...

pthread_join seems to modify my loop index

c,multithreading,for-loop,pthreads,pthread-join
My code (see below) produces an odd behaviour. The output is: Testing whether there are problems with concurrency ...rc is 0. i is 0 .rc is 0. i is 0 .rc is 3. i is 1 .rc is 0. i is 0 .rc is 3. i is 1 .rc is...

Issues when trying to compile with multidimensional array [closed]

c++,c,pthreads
I am trying to write a pthred code in c for matrix multiplication. It works fine if I try with predefined multi-dimensional arrays but don't work if I try generate the matrix array dynamically. Here is my code #include <pthread.h> #include <stdio.h> #define M 2 #define K 2 #define N...

Reuse thread struct after thread_join in C

c,multithreading,stack,pthreads
I have an array of thread variables on the stack, which the main thread later joins with. I have to run the same number of threads again later, and was wondering if I can still use the same array of thread structs to create new threads, or if the thread...

Conditionnal Variable doesn't wake up

c++,pthreads
I have to build a pizzeria in c++ for a school project. In order to do that I have to use thread and CondVar. I'm doing this for Condvar : class Condvar { pthread_cond_t m_cond_var; Mutex _mut; public: Condvar() { _mut.init(); pthread_cond_init(&m_cond_var, NULL); } ~Condvar() { pthread_cond_destroy(&m_cond_var); } void wait()...

C - pthread_create - Clang GCC difference

c,gcc,pthreads,clang
Passing the argument to pthread_create with clang (3.6.1) and gcc (5.1.0) brings different results for a strange case, illustrated here: pthread_t spawn_bserver_thread(uint16_t portno) { pthread_t tid; int32_t sockfd = create_bserver(portno); set_nonblocking(sockfd); exit_ncurses(); printf("%d\n", sockfd); if(pthread_create(&tid, NULL, bserver_thread, &sockfd) != 0) error("pthread_create"); return tid; } and bserver_thread: static void * bserver_thread(void...

Performance implications of a large number of mutexes

c,multithreading,pthreads
Suppose I have an array of 1,000,000 elements, and a number of worker threads each manipulating data in this array. The worker threads might be updating already populated elements with new data, but each operation is limited to a single array element, and is independent of the values of any...

How do I pass an integer into the pthread_create function from argv? (C)

c,casting,pthreads,argv
For this program I pass in numbers through the command line and then have a multithreaded program that takes each argument, calculates its factors, then prints them. I know c++, but I'm rough with c and can't seem to get the casting down correctly for this program. Specifically when I...

what's the difference between pthread_attr_setschedparam and pthread_setschedparam?

linux,pthreads,posix,scheduling
what's the difference between pthread_attr_setschedparam and pthread_setschedparam? How should I make decision to choose one to use?

Use Commands from argv to Initialize a Global Mutex

pthreads,global-variables,global,mutex,argv
What I wish to do is to define a global mutex using data from argv. Not a problem, except that I also want this mutex to be global. This isn't global:: int main (int argc, char **argv) { int arg_1 = atoi(argv[1]); pthread_mutex_t mutex[arg_1]; return 0; } And this isn't...

Pthread conditionals

c,multithreading,pthreads
I can post my code if necessary, but my question is primarily conceptual. I am implementing Gaussian elimination with threading. I have p pthreads operating on an nxn matrix in column major order. Before any p-thread can start operating on a column, row operations must be done to move the...

Segmentation fault while creating a number of threads entered by the user

c,multithreading,pthreads
I'm trying to solve the Producer-Consumer problem using pthreads and a buffer in the form of a vector. I want to be able to input the amount of threads I will have of Producers and Consumers. I get a segmentation fault as soon as I enter both values. I'm compiling...

Optional Cancellation points

multithreading,pthreads,posix
I just want to know the meaning of optional Cancellation point. Like we have mandatory cancellation point which means cancellation point shall occur when any of the functions that comes under mandatory cancellation points is called in a thread. So, is it like for optional one , cancellation point may...

Using threads with socket in c

c,sockets,pthreads
I have this program that is creating a thread for every call to the server. It compiles with no errors however it never makes it to the printf('before while') statement however it does get passed the bind #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <strings.h> #include <string.h> #include...

What's a good strategy for clean/reliable shutdown of threads that use pthread barriers for synchronization?

c,pthreads,pthread-barriers
I've got a pthread-based multithreaded program that has four threads indefinitely executing this run-loop (pseudocode): while(keepRunning) { pthread_barrier_wait(&g_stage_one_barrier); UpdateThisThreadsStateVariables(); pthread_barrier_wait(&g_stage_two_barrier); DoComputationsThatReadFromAllThreadsStateVariables(); } This works pretty well, in that during stage one each thread updates its own state variables, and that's okay because no other thread is reading any other thread's...

Multithreaded program not producing desired output

c,linux,multithreading,pthreads
I am writing a code that creates 10 threads and executes those threads with even thread ids first and then executes all those with odd thread ids next. I'm using the POSIX threads library. Here is the code I wrote: #include "stdlib.h" #include "pthread.h" #include "stdio.h" #define TRUE 1 #define...

Improving a simple function using threading

c,multithreading,pthreads
I have written a simple function with the following code that calculates the minimum number from a one-dimensional array: uint32_t get_minimum(const uint32_t* matrix) { int min = 0; min = matrix[0]; for (ssize_t i = 0; i < g_elements; i++){ if (min > matrix[i]){ min = matrix[i]; } } return...

Segmentation fault error in a program for counting no of occurences of a word in a file using threads

c,linux,multithreading,file,pthreads
So i have the following problem: Implement a program that gets as arguments a file name followed by words. For each word, create a separate thread that counts its appearances in the given file.Print out the sum of the appearances of all words. my code is: #include <stdio.h> #include <stdlib.h>...

Pthread arg in C

c,linux,pthreads
I am trying to create n threads passing as argument an integer identifier. My problem is that when I read that identifier from the thread shows strange things. This is my code (simplified) th_clientes = malloc(sizeof(int) * n_clientes); arg_clientes = malloc(sizeof(int) * n_clientes); t_espera = malloc(sizeof(int) * n_clientes); // Create...

Simulating a train with threads

c,multithreading,pthreads
Edit : I think i'm making somthing wrong because when I compile and run my binary twice, I get differents outputs.. I'm trying to understand threads with pthread so I did a little code to simulate the passage of a train on a bridge (who can handle only 2 train...

Correctly waiting for a thread to terminate in C

c,pthreads
This code plays a sound clip by creating a thread to do it. When bleep() runs, it sets the global variable bleep_playing to TRUE. In its main loop, if it notices that bleep_playing has been set to FALSE, it terminates that loop, cleans up (closing files, freeing buffers), and exits....

Multithreaded C Lua module leading to segfault in Lua script

c,linux,multithreading,lua,pthreads
I've written a very simple C library for Lua, which consists of a single function that starts a thread, with said thread doing nothing but looping : #include "lua.h" #include "lauxlib.h" #include <pthread.h> #include <stdio.h> pthread_t handle; void* mythread(void* args) { printf("In the thread !\n"); while(1); pthread_exit(NULL); } int...

Setting all TLS (thread local storage) variables to a new, single value in C++

c++,multithreading,asynchronous,pthreads
I have a class Foo with the following thread-specific static member: __declspec(thread) static bool s_IsAllAboutThatBass; In the implementation file it is initialized like so: __declspec(thread) bool Foo::s_IsAllAboutThatBass = true; So far so good. Now, any thread can flip this bool willy nilly as they deem fit. Then the problem: at...

Does Java JVM use pthread?

java,linux,osx,jvm,pthreads
Does JVM on Mac OS X use pthread to create threads? What about on Linux distributions, is it now default way to create threads for JVM on all distributions?...

Return a function while daemon thread is working in the background (c++)

c++,linux,linux-kernel,pthreads,daemon
I want to return function 'A' with some return value(let's say '0') while a daemon thread started running inside this function but may not finished. Is that even possible?