Menu
  • HOME
  • TAGS

GNU/Linux thread implementation

c,linux,pthreads

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...

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

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; } ...

pthread_join seems to modify my loop index

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...

PHP - Multithread a function with pthreads

php,multithreading,pthreads

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...

Linux pthread Producers and Consumers

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...

Reading from a file in different threads in C

c,multithreading,pthreads

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 - Waiting For Multiple Threads to Terminate

c,multithreading,pthreads,terminate

You want &mapperThreads[i] instead of &mapperThreads[N] in each case.

Applying two or more mutexes to a section of code

c++,pthreads,mutex,deadlock

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...

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

multithreading,pthreads

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...

How to Detect a Spurious Wakeup

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....

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

c++,qt,pthreads

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...

Force unlock a mutex that was locked by a different thread

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...

Slow pthreads, does not appear to be mere overhead

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 pthreads, in pool tasks, ob_flush and flush cause crash

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....

Blocking in pthread_join()

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 logic for error condition

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...

Retrieve pthread_create's arg from outside the thread?

multithreading,pthreads

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....

Unix c program to calculate pi using threads

c,unix,pthreads

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...

Understanding posix barrier mechanism

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...

No prints from the second thread - pthreads with mutex locks

c,multithreading,pthreads

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...

Issues when trying to compile with multidimensional array [closed]

c++,c,pthreads

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....

Sending a glib signal across threads

c++,multithreading,pthreads,signals,glib

Emit the signal from an idle callback which returns FALSE.

pthread_barrier_wait hangs after creation of all threads

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....

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

c,casting,pthreads,argv

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,...

luajit/physicsfs mutex deadlock

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?

c,pthreads

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....

Can't synchronize more than 2 threads with pthread_mutex_lock

c,pthreads,mutex

Two bugs memset(count, 0, 49); should be: memset(count, 0, sizeof(count)); And.. count[i] = d->vec[j]; should be: count[i]++; ...

Reuse thread struct after thread_join in C

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...

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

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()...

Two-Lock Concurrent Queue Algorithm implementation issue

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...

creating threads using pthread.c

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...

c++ issue passing information to pthreads

c++,pthreads,corruption

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...

Issue creating multiple threads with pthreads

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().

C Pthreads numbers

c,multithreading,pthreads

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...

what's the difference between pthread_attr_setschedparam and pthread_setschedparam?

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...

Why is the segmentation Fault error occuring

c,pthreads

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...

Pthread arg in C

c,linux,pthreads

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); ...

Calculate the sum of two numbers using thread

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....

Thread synchronisation for C++ map

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...

Correctly waiting for a thread to terminate in C

c,pthreads

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 when creating pthreads

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....

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

c++,pthreads,sfml

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...

A strange result in a simple pthread code

c,multithreading,pthreads

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...

What is the meaning of “statically allocated”?

c,pthreads

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...

Passing in arguments to pthread results in duplicates C

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.

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

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.

Necessity of pthread mutex

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...

Does Java JVM use pthread?

java,linux,osx,jvm,pthreads

Yes, HotSpot JVM (i.e. Oracle JDK and OpenJDK) uses pthreads on Linux and on Mac OS X.

pthread_mutex_errorcheck_np initialization error

c,pthreads,mutex

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....

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

pthreads,member-function

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.

phread_cond_broadcast race condition

multithreading,pthreads

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...

PHP thread - run method not being called

php,pthreads

In the while loop, $a never changes and causes an infinite loop (it's always equal to zero).

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

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...

waitpid for child process not succeeding

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...

Understanding parallel thread execution

c,multithreading,pthreads

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...

C++ erroring creating n pthreads-

c++,compiler-errors,pthreads

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) *...

Conditionnal Variable doesn't wake up

c++,pthreads

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...

Passing arguments to a thread

c,pthreads

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....

Pthreads and signals C++

c++,pthreads,signals

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...

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

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...

Initialise thread pool

c,multithreading,pthreads

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)...

Some pthread code…why is it running slow?

c,pthreads

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...

freopen() on OSX 10.10.3

osx,pthreads,io-redirection

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....

Optional Cancellation points

multithreading,pthreads,posix

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,...

Segmentation Fault after pthread_create()

c,segmentation-fault,pthreads

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 ...

Performance implications of a large number of mutexes

c,multithreading,pthreads

(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...

Pthread id and sleep

c,multithreading,pthreads

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....

Improving a simple function using threading

c,multithreading,pthreads

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...

Thread blocking on sem_wait causes other threads to hang

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...

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

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,...

interaction between Queue and pool of Threads?

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...

pthred_exit return variable static vs global scope

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...

Mutex or not to Mutex?

pthreads,mutex

Do I need a Mutex for that? Assuming something like: int A[1024]; Short answer (for C): No....

Use Commands from argv to Initialize a Global Mutex

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...

mmap() and pthreads - copy VMA

c,linux-kernel,pthreads,mmap

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...

Assure the execution of every thread

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...

need to know how to interrupt all pthreads

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...

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

c,multithreading,pthreads

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...

Using threads with socket in c

c,sockets,pthreads

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....

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

c,pthreads,pthread-barriers

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...

Interruption in a linux multithreaded app generate SIGSEGV

c++,c++11,pthreads,signals

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...

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

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....

Simulating a train with threads

c,multithreading,pthreads

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 =...

Thread creation inside constructor

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...

C - pthread_create - Clang GCC difference

c,gcc,pthreads,clang

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.

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

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...

What if a condition variable signals to a locked thread?

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...

Test for std::thread native handle implementation

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...

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

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...

Why are these pthreads segmentation faults possible?

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...

Multithreaded C Lua module leading to segfault in Lua script

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...

Pthread join segmentation fault

c,multithreading,pthreads

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...

Pthread conditionals

c,multithreading,pthreads

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...