Just reading the relevant lines from book and the example shared by you, it is clear that it is related to specific implementation of POSIX threads on GNU/Linux In GNU/Linux, threads are implemented as processes. Hence, Whenever you call pthread_create to create a new thread, Linux creates a new process...
c++,linux,linux-kernel,pthreads,daemon
Just detach the thread and then return from the function. int createThreadAndReturn() { std::thread(daemon_thread_function).detach(); return 0; } ...
c,multithreading,for-loop,pthreads,pthread-join
I think your problem is with the pthread_join. From the man page: int pthread_join(pthread_t thread, void **retval); ... If retval is not NULL, then pthread_join() copies the exit status of the tar‐ get thread (i.e., the value that the target thread supplied to pthread_exit(3)) into the location pointed to by...
The basic problem is that arrays are not thread safe, pthreads provides array-like interfaces on all Threaded objects; This means you can use Threaded objects in place of arrays in a multi-threaded context. <?php function demanding(...$params) { /* you have parameters here */ return array(rand(), rand()); } class Task extends...
c,multithreading,concurrency,pthreads,producer-consumer
Incorrect producer Consider your producer: sem_wait(&producer_semaphore); pthread_mutex_lock(&write_index_mutex); my_write_index = write_index; write_index = (write_index + 1) % BUFFER_SIZE; total_produced_sum += producer_id; pthread_mutex_unlock(&write_index_mutex); // Producer #1 stops right here. buffer[my_write_index] = producer_id; sem_post(&consumer_semaphore); Let's suppose the following sequence happens: Producer #1 runs until the comment above and then stops. Suppose its my_write_index...
Each open FILE has only one file pointer. That has one associated FD, and one file position (file offset as you put it). But you can fopen the file twice (from two different threads or for that matter from the same thread) - as your edit now implies you are...
c,multithreading,pthreads,terminate
You want &mapperThreads[i] instead of &mapperThreads[N] in each case.
Essentially if you need two mutexes to perform a task, mutex_1 and mutex_2, if thread_A grabs mutex_1 and thread_B grabs mutex_2, they are stuck in a deadlock because they are both waiting for the other mutex to become available, but they never will because the other is waiting too. That...
As you can see in the specification, for example here, pthread_mutex_lock() has a int return value. Apart from the trivial/obvious error causes, such as "invalid argument" etc, there is one which can actually be considered a "threat". Especially a threat to people who do not check return values. This threat...
java,linux,multithreading,pthreads,posix
What spurious wakeups are not sleep() is not subject to spurious wakeups. The low-level system call it uses to sleep may be, but Java takes care of this detail for you, re-entering the system call if it's woken up prematurely. As a user you are not exposed to spurious wakeups....
You should pass a pointer to an instance of the class as the arg during thread creation. That way, rather than marking arg as "not used" you can do this inside your static method: void *MainWindow::readerThreadEntryPoint(void *arg) { MainWindow* self = static_cast<MainWindow*>(arg); From then on you can use self similar...
c,multithreading,pthreads,freebsd
I have come up with a workable method to deal with this situation. As I mentioned before, FreeBSD does not support robust mutexes so that option is out. Also one a thread has locked a mutex, it cannot be unlocked by any means. So what I have done to solve...
c,multithreading,performance,pthreads
rand() "is not reentrant or thread safe". Your threads are likely contending on something internal to rand(). Replace rand() with rand_r()....
php,apache,pthreads,threadpool,flush
Multiple threads should not write standard output, there is no safe way to do this. Zend provides no facility to make it safe, it works by coincidence, and will always be unsafe....
c,multithreading,unix,pthreads
Yes - the main thread blocked on thrs[0] will not get the result from thrs[2] until after thrs[[0] and thrs[1] have also exited. If you need more flexibility one option is to do something like having the threads post their results in a queue or signal in some other way...
c,timer,pthreads,delay,multitasking
I suggest you add a "pthread_mutex_t" to handle file writing: 1. declare mutex_writing as global variable 2. is_writing[EXTS_LIMIT] as global variable //for each sensor:boolean indicating writing status 3. writingtime[EXTS_LIMIT]//store the last writing time for a given sensor 4. index //added to arg_struct in order to identify the sensor and modify...
I don't think we can maintain a map of external thread ids to unique ids because of the reuse problem. The same thread id could have multiple unique ids. You can, as long as in this map you only keep the external thread IDs corresponding to currently running threads....
There are numerous problems with that code. Your specific problem is that, in C, variable length arrays (VLAs) are not permitted at file scope. So, if you want that array to be dynamic, you will have to declare the pointer to it and allocate it yourself: int N, T; double...
c,multithreading,pthreads,posix
What your barrier is doing is preventing Thread 1 from producing any output before Thread 2 is created. After both threads are created, both cross the barrier and are unblocked. After that you are not asserting any control as to how they are interleaved. So, thread 1 happens to get...
The first thread increments globalVarX to 1000 and the second thread has nothing to do. I suggest: Locking one increment instead of the whole loop. Give the other thread the opportunity to increment also by calling sched_yield(), because if one thread increments globalVarX to 1000 in its time slice there...
You need to include #include<stdlib.h> to get malloc()'s prototype should put the executable code block/statements within a function in C. Which both in your code is not the case and since for() loops are not within any function there is a valid error....
c++,multithreading,pthreads,signals,glib
Emit the signal from an idle callback which returns FALSE.
multithreading,pthreads,barrier
The barrier expects to be waited on NUM_THREADS times, but only one thread, the main thread, actually calls pthread_barrier_wait. If you want to synchronize main with your worker threads, you'll need to initialize the barrier for NUM_WORKER_THREADS + 1....
The problem is that each thread uses the same array for the factors, without any synchronization. But if each thread had to get a lock for the array before running, they would in effect all run in sequence which would defeat the purpose of threading. argv[0] is the program name,...
lua,pthreads,mutex,deadlock,luajit
I still don't really know what the hell is going on, but while trying to further debug the mutex in gdb I LD_PRELOADed libpthread.so to the gdb process, and suddenly it worked. Then I tried just preloading it to luajit without gdb, also works. Then I dug further into physfs...
Can I call pthread_join on a pthread_detached thread? No. I'm wondering if the parent will still wait for the children to finish executing. It's undefined behaviour. pthread_join says: The behavior is undefined if the value specified by the thread argument to pthread_join() does not refer to a joinable thread....
Two bugs memset(count, 0, 49); should be: memset(count, 0, sizeof(count)); And.. count[i] = d->vec[j]; should be: count[i]++; ...
c,multithreading,stack,pthreads
When a thread exits, it's done. You can't "reuse" it - create another one. You can reuse your array of course - but not the values inside of it. (ie. need to pthread_create again) The question you cite was asking about the maximum number of /concurrent/ threads - OP was...
c++,multithreading,asynchronous,pthreads
Here is a light weighted implementation of "Plan A" with C++11 Standard atomic variable and thread_local-specifier. (If your compiler doesn't support them, please replace to vendor specific facilities.) #include <atomic> struct Foo { static std::atomic<unsigned> s_TokenGeneration; static thread_local unsigned s_LocalToken; static thread_local bool s_LocalState; // for central thread void signalResetIsAllAboutThatBass()...
c,multithreading,algorithm,pthreads,concurrent-programming
The following FTP link works fine for me: ftp://ftp.cs.rochester.edu/pub/packages/sched_conscious_synch/concurrent_queues/concurrent_queues.tar.gz...
c,multithreading,pthreads,semaphore
I figured it out, I didn't think about the code properly. The threads are running concurrently so there is no way to decide what the value of glob will be. If two threads are running, the first one might be 5 values into the loop and the second thread might...
threadData is local to your for loop... it goes out of scope on each iteration, so a pointer to it is not valid in your showData() routine. You could instead allocate it dynamically and delete it at the end of showData. You probably want to return the threads data to...
c,linux,multithreading,ubuntu,pthreads
197% = 2 threads exercising the cpu doing sqrt() in a loop, plus one thread which is not using any cpu because it is waiting for the other threads to finish in pthread_join().
Apart from some "smaller" issues like the randomly placed pthread_exit() statements, the wrong signature of your thread functions (they must be void* f(void*) , the bad choice for your while loops within add() and sub() and a few other things, your code looks good. You are probably aware, that your...
linux,pthreads,posix,scheduling
pthread_setschedparam() sets both the scheduler policy and scheduler parameters for an existing thread. pthread_attr_setschedparam() and pthread_attr_setschedpolicy() set the scheduler parameters and scheduler policy respectively for a thread attributes object (type pthread_attr_t). This will set the scheduler parameters and scheduler policy for any new threads that are then created using that...
You never check for bound of colatz_nums. You are accessing it using j and increments it without limiting it to 24. You first execute colatz_nums[0] = 8 which sets the first value of the array to 8. Then you go to compare it with 1 which it is not and...
Your are probably not allocating enough memory for your array of pthread_ts. Change: th_clientes = malloc(sizeof(int) * n_clientes); to: th_clientes = malloc(sizeof(pthread_t) * n_clientes); ...
c,unix,segmentation-fault,pthreads
The name of the array, global points to the base address of the array. You can simply pass that and use the same inside your thread function. However, just to mention a logical point, if you're passing global as a parameter to sum_thread() function, it need not be a global....
c++,multithreading,dictionary,pthreads
I understand that reading using the [] operator, or even modifying the elements with it is thread safe, but the rest of the operations are not. Do I understand this correctly? Well, what you've said isn't quite true. Concurrent readers can use [] to access existing elements, or use...
Hmm... pthread_join should do the job. As far as I remember the thread has to call pthread_exit...? /* bleep thread */ void *bleep(void *) { /* do bleeping */ pthread_exit(NULL); } /* main thread */ if (pthread_create(&thread, ..., bleep, ...) == 0) { /* ** Try sleeping for some ms...
c++,segmentation-fault,pthreads
I suppose the problem is that your arg parameter is on stack of your createThreads function: struct threadData threadData[k]; so once your thread gets created and run, and createThreads returns, threadData is no longer valid, so your thread function should not touch argument data. Otherwise its undefinded behaviour and crash....
According to the docs: As a sound stream, a music is played in its own thread in order not to block the rest of the program. This means that you can leave the music alone after calling play(), it will manage itself very well. So you don't really need to...
For output 1: your main function only create a pthread, and let it run without waiting for it to finish. When your main function return, Operating system will collect back all the resources assigned to the pprocess. However the newly created pthread might have not run. That is why you...
Statically allocated means that the variable is allocated at compile-time, not at run-time. In C, this can be a global variable at the file scope or a static variable in a function. A good overview is found here: http://en.wikipedia.org/wiki/Static_memory_allocation Variables on the stack (i.e., local variables in functions that do...
c,multithreading,file-io,pthreads
I'm not seeing a problem with passing individual files, but if you pass directories containing multiple files, grep_directory() will start multiple threads with the same value of id, which will all store their filename in the same place.
c,linux,multithreading,osx,pthreads
MacOSX and Linux implement pthread differently, causing this slow behavior. Specifically MacOSX does not use spinlocks (they are optional according to ISO C standard). This can lead to very, very slow code performance with examples like this one.
c,multithreading,pthreads,mutex
Yes, you need synchronization, because all thread are modifying the sum at the same time. Here's example: You have array of 4 elements [a1, a2, a3, a4] and 2 threads t1 and t2 and sum. To begin let's say t1 get value a1 and adds it to sum. But it's...
You need to use PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP when initializing the mutex statically with '=' (note the extra _INITIALIZER). PTHREAD_MUTEX_ERRORCHECK_NP is for when you're initializing it at runtime using pthread_mutex_init(3). It is better to use -pthread than -lpthread by the way. It sets preprocessor flags to make some functions reentrant for example....
Although I was suspected to the binding that I described, it was not the source of my problem and it works correctly. The problem was waiting while loops which were affected by optimizer! Using volatile keyword solved my problem.
Condition variables need to be paired with a condition over some shared state (often called a "predicate") - that's why they're called condition variables. So for example to start the workers you could use a simple global flag variable: int start_work = 0; /* Protected by WORKlock */ Then in...
In the while loop, $a never changes and causes an infinite loop (it's always equal to zero).
c,asynchronous,concurrency,pthreads,threadpool
I presume it is your intention is that a thread will request the asychronous work to be performed, then go on to perform some different work itself until the point where it requires the result of the asynchronous operation in order to proceed. In this case, you need a way...
c,linux,process,pthreads,waitpid
This is difficult to debug without code, but errno 10 is ECHILD. Per the man page, this is returned as follows: ECHILD (for waitpid() or waitid()) The process specified by pid (waitpid()) or idtype and id (waitid()) does not exist or is not a child of the calling process. (This...
If you want to get the desired output, you should use two semaphores instead of one. Each thread should wait on its own semaphore and post the other thread's semaphore after it is done with each loop iteration. The main thread can create one semaphore with a value of 1...
The first problem is that you're trying to compile C with a C++ compiler. This conversion: pthread_t *threads = malloc(sizeof(pthread_t) * numThreads); from an untyped void* pointer returned by malloc, to a typed pthread_t* pointer, is allowed in C but needs a cast in C++. pthread_t *threads = static_cast<pthread_t*>(malloc(sizeof(pthread_t) *...
This: _mut.lock(); pthread_cond_wait(&m_cond_var, _mut.getMutex()); _mut.unlock(); fundamentally misunderstands how pthreads condition variables work. The mutex argument to pthread_cond_wait() isn't just there to be an embuggerance: a condition variable must be paired with a condition over some shared state (often called a predicate), and the mutex passed should be the mutex that...
It is because &structure is always the same for your NUM_T calls to pthread_create. You may try estrutura_main structure[NUM_T]; for(i=0;i<NUM_T;i++){ structure[i].j=i; pthread_create(&threads[i], NULL, sum, (void*)&structure[i]); } then each thread gets a pointer to different instance....
A condition variable is near-useless without a predicate, a conditional state that dictates what has changed. The condition variable is little more than a signaling mechanism to announce that "something" may have changed, but you still need to manage the "what". And that mutex is what protects that "what". For...
c++,pthreads,condition-variable
The behavior of a condition variable is that of releasing the lock and waiting (atomically) and then re-acquiring the lock when the thread is signaled. In your code, one thread is signaling the other while holding the mutex, and the implication is that the woken up thread is going to...
Create a queue of jobs (this could be as simple as a linked list), protected by a mutex. Pair this with a condition variable that is broadcast signalled when a job is added to the queue. The threads can then wait for a job with code like: pthread_mutex_lock(&queue_lock); while (queue_is_empty)...
It is because you have thread lock starvation effect. When some thread doesn't own the resource, but constantly checks for it inside a critical section, thus preventing actual owner to obtain the lock and release the resource. This occurs usually when the time of operation outside of lock is too...
The solution that is working for me can be found in R.'s answer to Is close/fclose on stdin guaranteed to be correct? Basically, the idea is to open the file you want to redirect to, duplicate that to stdin, and then close the file description just opened....
POSIX requires certain functions to be a cancellation point and says cancellation points may occur in certain functions (optional cancellation points). You can read the entire list of mandatory and optional cancellation points from the manual pthreads(7): Cancellation points POSIX.1 specifies that certain functions must, and certain other functions may,...
In your case, consider replacing conn.sockfd = *((int*)sockfd); by conn.sockfd = (int)sockfd; You didn't have passed the sockfd variable as a pointer so you cannot dereference it. Take a look at : http://en.wikipedia.org/wiki/Dereference_operator ...
(A very partial & possibly indirect answer to your question.) Have once scored a huge performance hit trying this (on a CentOS) raising the number of locks from a prime of ~1K to a prime of ~1M. While I never fully understood its reason, I eventually figured out (or just...
Your argument passing is fine. But you are not passing the value to sleep. It should be sleep(*p); p points the address of i (from the function th()). You need to dereference the pointer to get the value....
Having more threads than cores available to run them on is always going to be slower than a single thread due to the overhead of creating them, scheduling them and waiting for them all to finish. The example you provide is unlikely to benefit from any optimisation beyond that which...
c,multithreading,pthreads,semaphore,fifo
In main(), you have this line: queue_t *commandQueue = calloc(1, sizeof(queue_t)); This makes commandQueue a local variable of main. Your other functions use a global variable also named commandQueue. This makes me think that you did not intend for commandQueue to be redeclared in main. So change the above line...
multithreading,concurrency,pthreads,concurrent-programming,pthread-join
The only work here that can be done in parallel is the loop: for(int i=0;i<10000;i++) temp%i; // do some CPU intensive work gcc, even with the minimal optimisation level, will not emit any code for the temp%i; void expression (disassemble it and see), so this essentially becomes an empty loop,...
c++,multithreading,pthreads,threadpool
1- is this a good way to deal with this problem. It's a well known pattern, and used in many applications. You can use a std:queue to implement this. Just protect the read/write operations on it using a std:mutex. Also you should have a condition variable or semaphore, where...
pthreads,static-variables,pthread-join
Almost certainly it's because the size of int and void * differ on your platform, so when pthread_join() writes a void * value through the int * pointer you gave it, it overwrites adjacent memory. The different declaration of r1 and r2 changes the layout of the variables enough to...
Do I need a Mutex for that? Assuming something like: int A[1024]; Short answer (for C): No....
pthreads,global-variables,global,mutex,argv
You can use dynamic allocation, just like you would for any other type. The only difference here is that dynamically allocated mutexes must be initialised with pthread_mutex_init(): pthread_mutex_t *mutex; size_t n_mutex; int main (int argc, char **argv) { size_t i; if (argc < 2) return 1; n_mutex = atoi(argv[1]); if...
I mmap() an anonymous VMA. How do pthreads handle that VMA? "pthreads" (user-space library for threads in Linux) have no special handling of new VMA's from mmap. I want that the vma with its memory is copied for every thread. You can't, because every thread of single process have...
c,multithreading,pthreads,posix,pthread-join
The reason you always see the same value You are printing your pointer as a integer. data points to your variable i in your main. The address of i will not change, hence the same value being printed. Printing the value of i What you want to do is dereference...
multithreading,pthreads,signals
This minimal example seems to function in the manner you want - all the threads except the main thread end up waiting in wait_until_death(): #include <stdio.h> #include <pthread.h> #include <signal.h> #include <unistd.h> #define NTHREADS 10 pthread_barrier_t barrier; void wait_until_death(int sig) { sigset_t mask; sigemptyset(&mask); sigaddset(&mask, sig); sigprocmask(SIG_UNBLOCK, &mask, NULL); for...
Is this a university course or something? The problem is reported by the compiler (gcc) if only you ask it to enable warnings. Whoever is "teaching" you c should have told you that. meh.c: In function ‘printState’: meh.c:25:21: warning: unused parameter ‘i’ [-Wunused-parameter] void printState(int i){ ^ meh.c: In function...
This line GetToken = strtok_r(TmpBuffer," ",&SavePtr); seems to be a problem, since TmpBuffer is a pointer to char, which points to nothing... Comment it out, or allocate some memory, populate it, and assign it to TmpBuffer....
Having two flags and using something like the following should work: for (;;) { pthread_barrier_wait(&g_stage_one_barrier); + | UpdateThisThreadsStateVariables(); | | pthread_mutex_lock(&shutdownMtx); | Zone 1 pendingShutdown = !keepRunning; | pthread_mutex_unlock(&shutdownMtx); | | pthread_barrier_wait(&g_stage_two_barrier); + | if (pendingShutdown) | break; | Zone 2 | DoComputationsThatReadFromAllThreadsStateVariables(); | } shutdownMtx should protect the setting...
I believe that you can safely ignore the error. A StackOverflow member with a reputation in the top 0.25% of members (!) says that this warning "Could not load shared library symbols for linux-vdso.so.1." is something you can safely ignore. To see the post, go here: Could not load shared...
c++,pthreads,function-pointers,argument-passing
C++ is picky when it comes to casting. Replace void *InThread_func(struct arg_struct *); by void *InThread_func(void *my_data); and it should solve the problem. Since this is C++ I'd recommend using std::thread is those are available to you....
The problem with your code is that all pthread_mutex_lock(&mutex); does is wait until mutex is no longer locked, and then locks it. It doesn't actually check what the value of t is. What you're really looking for is a condition variable: #include <pthread.h> #include <stdio.h> #include <time.h> pthread_mutex_t mutex =...
c++,multithreading,static,pthreads
As for your problem, you a pointer to a (non-static) member function is not the same as a pointer to a member function. Non-static member functions needs an instance of an object to be called on. There are a couple of ways to solve this: If you insist on using...
The problem is most likely that you have no control over when the thread starts to run, so the spawn_bserver_thread function may exit before the thread function starts, meaning the sockfd variable goes out of scope and the pointer argument to the bserver_thread function is no longer valid.
c,multithreading,unix,pthreads
An example, it's pretty simple — first make a pipe with pipe(). It creates two file descriptor — one for reading, and the second for writing. Here we calling it two times to have both read and write sides. Then we calling fork (that makes a second thread), and write/read...
c,multithreading,pthreads,mutex,condition-variable
You have to use the same mutex when the in() thread sets isEmpty = false and the out() thread tests while (isEmpty). Otherwise, this can happen: out() thread tests isEmpty, finds it is true; in() thread sets isEmpty to false and signals the condition variable (but no-one wakes up, beacuse...
multithreading,c++11,pthreads,native,handle
Introduction There's nothing saying that a certain MACRO, or equivalent, will be available for the preprocessor (that would yield what thread-implementation a certain implementation is using). If we instead were to inspect the returned value (more specifically the returned type) of std::thread::native_handler (std::thread::native_handle_type) one might think that it would yield...
c,linux,multithreading,file,pthreads
First off, your code is terribly formatted. It's not even consistent. It also does not appear you are compiling with warnings enabled. If you are a university course and they did not tell you how do format the code and compile with warnings, I strongly suggest you ask your tutors...
php,multithreading,reference,segmentation-fault,pthreads
1) The whole context is copied when the thread is started. You have to keep refcounts > 0 until the stacked objects are actually executed by the worker thread. 2) The reference counting built into variables in PHP was never prepared for multi-threading, many api functions decrement and increment refcounts...
c,linux,multithreading,lua,pthreads
Why does the Segfault Happen in the Lua Module? Your Lua script exits before the thread has finished which causes the segfault. The Lua module is unloaded using dlclose() during the normal interpreter shutdown, and so the thread's instructions are removed from memory, and it segfaults on reading its next...
Lets take these lines: int *array; array=numbers; pthread_create(&threads[0], NULL, increment, (void *) &array); Here you pass the address of the variable array to the thread function, but while array itself points to the array, the address of the variable does not. If you want to use temporary variables, just use...
You only need to hold the cond_mutex while you are accessing pivotReady[pivot], because that's the only shared state it protects. You also need to use pthread_cond_broadcast() rather than pthread_cond_signal(), because you need all the waiting threads to proceed once the pivot is ready. After a minor refactoring so that the...