multithreading,pthreads,barrier , pthread_barrier_wait hangs after creation of all threads


pthread_barrier_wait hangs after creation of all threads

Question:

Tag: 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 = (intptr_t) tid;
    printf("Hello from thread %d\n", temp);
}

int main()
{
    pthread_t threads[NUM_THREADS];
    int rc;
    pthread_barrier_init(&barrier, NULL, NUM_THREADS);

    for(int i = 0; i < NUM_THREADS; ++i) {
        rc = pthread_create(&threads[i], NULL, threadFun, (void *) i);
        if(rc)  {
            printf("Error creating thread %d\n", i);
            exit(-1);
        }
    }

    pthread_barrier_wait(&barrier);
    printf("Hello from main!\n");

    for(int i = 0; i < NUM_THREADS; ++i) {
        pthread_join(threads[i], NULL);
    }
    pthread_barrier_destroy(&barrier);

    return 0;
}

Currently, my program prints some non-deterministic assortment of "Hello from thread " statements, and hangs before printing "Hello from main!"; however, it always prints 8 thread messages. Thus, all the threads are created.

Why is it still hanging?

Thanks, erip


Answer:

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.


Related:


Visualvm thread started count


java,multithreading,profiling,visualvm
Am monitoring a java application for thread lock scenario, In visualvm under monitor tab, Live threads : 112 Live Peak : 126 Daemon thread : 99 Total started : 135,742 What does this mean? I feel its not right to have so much total started threads count. Is there any...

Images not appearing on WPF form when loading asynchronously


c#,wpf,multithreading,listbox,backgroundworker
I'm attempting to display (in a ListBox with a custom DataTemplate) a series of BitmapSource frames (thumbnails) extracted from a multi-page tiff image. When I process the tiff on the UI thread, and either directly add the images to a listbox's item collection or add them to a bound ObservableCollection,...

java multithreading start() and run() [duplicate]


java,multithreading
This question already has an answer here: Java: What's the difference between Thread start() and Runnable run() 10 answers Below is my Multithreading class: public class Multithreading extends Thread{ public void run(){ for(int i=1;i<5;i++){ try{ Thread.sleep(500); }catch(InterruptedException e){ System.out.println(e); } System.out.println(i); } } public static void main(String args[]) {...

Set Label From Thread


vb.net,multithreading,winforms
Form1.vb Imports System.Threading Public Class Form1 Dim demoThread As Thread Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim Start As New Class1 Me.demoThread = New Thread( _ New ThreadStart(AddressOf Start.ThreadProcSafe)) Me.demoThread.Start() End Sub Delegate Sub SetTextCallback([text] As String) Public Sub SetText(ByVal [text] As String) ' InvokeRequired required...

Exclusive lock using key in .NET


c#,.net,multithreading,locking
I have used the lock statement in C# to exclusively execute a piece of code. Is there a way to do same based on a key. for e.g.: lock(object, key) { //code-here } I have a method which has some piece of code that is not thread-safe, but only if...

Java how to limit number of threads acting on method


java,multithreading,memory-management
I have java method in my web application doing heavy file operation. The thing is, if more than 5 threads come simultaneously (which will come in testing phase) it breaks down. I mean it cannot handle heavy traffic. That's why I want to handle maximum 5 requests at a time...

Recognizing Blocked Swing EDT


java,multithreading,swing
How to know that EDT is blocked (not visually but by inspecting the thread itself)? is there a way? I'm on the way to my final university task for graduation that have bunch of charts , but have little knowledge of Swing EDT (Java generally). have look at this piece:...

EXC_BAD_ACCESS error occurring when running recursive merge sort method in a thread


c++,multithreading,sorting,recursion
I'm having trouble with my C++ code in xCode. I've tried debugging and I can't fix it. I know it's roughly when my mergeSort() method calls my mergeNumbers() method. I know it's not the method itself because I've run the method without threading and it works just fine. It's when...

How to calculate how many times each thread executed a critical section in OpenMP?


c,multithreading,openmp
I have an OpenMP code, where I need to calculate how many times each thread executes the critical section, any idea how to do it? Code samples are highly welcomed.

C++ Ubuntu select() if serial interface has data on asynchronous read


c++,multithreading,ubuntu,asynchronous,serial-port
I´m writing an asynchronous serial data reader class for Ubuntu using C++ and termios and I´m facing difficulties checking is there is data available. Here is my code: #include <iostream> #include <string> #include <sstream> #include <vector> #include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <termios.h> class MySerialClass { public: MySerialClass(std::string port);...

Is there standard implementation for thread block/resume in java SE?


java,multithreading,wait
I need to block execution of a thread until resumed from another thread. So I wrote my own implementation using wait() method. Which seems to be working, but it is far from simple. Is there any ready to use solution? Preferably in java SE 6? Or do I have to...

hashmap iterator when used inside synchronized method


java,multithreading,hashmap
so let's say I have a Hashmap that looks like: key : value (string 1, queue 1) (string 2, queue 2) (string 3, queue 3) I also have a synchronized method that will access this hashmap, and an iterator is created inside the method: Iterator it = hashmap.iterator(); while(it.hasNext()){ Queue...

Multi-Threading error when binding a StringProperty


java,multithreading,javafx,javafx-8
I have a question about multi-threading and the binding of a StringProperty. I have a class CacheManager, which contains a Thread which updates my cache with the changes on the server. Now, I want to notify the user with a text and percentage of the progress (which are a Label...

Node.js and C/C++ integration: how to properly implement callbacks?


c++,node.js,multithreading
I am trying to implement a C++ extension to be integrated with node.js. This extension will internally invoke some blocking calls, so it needs to provide a non-blocking interface to the node.js world. As specified in https://nodejs.org/api/addons.html, there are two ways to implement non-blocking callbacks: a) By using a simple...

Invoke form showdialog is not modal


vb.net,multithreading,invoke
I have 2 forms, 1 MainForm and 1 Form2. I am trying to display Form2 as a modal form and background from MainForm. Here's what I have so far. The default MainForm appears and after 5 seconds it will show Form2 as a Modal form from a background thread. I...

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

C# Threading : Threads executed on incorrect object


c#,multithreading
Probably this is a dumb mistake by me, but I can't figure it out. So the scenario is that I retrieve a record from a database every 200ms, if there is one available. On each record, I start a thread. In this case it's a mail that is sent. QMail...

Calling Python code from Twisted


python,multithreading,twisted
First of all, I should say that this might more a design question rather than about code itself. I have a network with one Server and multiple Clients (written in Twisted cause I need these asynchronous non-blocking features), such server-client couple it's just only receiving-sending messages. However, at some point,...

How can I know the lock information in java?


java,multithreading,locking
Is there any tool or way that can get all the information about the locks in java? for example, if there is a java program, it creates two threads, and both threads require locks for some variable. Is there any tools that can output the information like which thread locks...

Atomic/not-atomic mix, any guarantees?


c++,multithreading,c++11,atomic
Let's I have GUI thread with code like this: std::vector<int> vec; std::atomic<bool> data_ready{false}; std::thread th([&data_ready, &vec]() { //we get data vec.push_back(something); data_ready = true; }); draw_progress_dialog(); while (!data_ready) { process_not_user_events(); sleep_a_little(); } //is it here safe to use vec? As you see I not protect "vec" by any kind of...

How to test running threads if they are terminating properly when they all done using JUnit


java,multithreading,junit
I've a server class which listens on a particular port number for the requests made by the clients. And for each client it opens a separate Thread of execution. But the problem is that server program gets hands every after few days and I had to restart that program...

Can you call dispatch_sync from a concurrent thread to itself without deadlocking?


ios,objective-c,multithreading,swift,grand-central-dispatch
I know you would deadlock by doing this on a serial queue, but I haven't found anything that mentions deadlocking by doing it on a concurrent queue. I just wanted to verify it wont deadlock (it doesn't seem like it would, as it would only block one of the threads...

Why does this code catch block not execute?


c++,multithreading,error-handling,try-catch
The catch handler is not run. But why? If the thread t is started before the try block, the catch handler runs. If the catch block's type does not match the type thrown, the program exits explaining that the thread terminated with an uncaught exception, suggesting that the exception is...

How do you start a function at a certain time in Python?


python,multithreading,events,time,condition
I have a list of timestamps, and I need to call a specific method when those timestamps are reached. Those timestamps are roughly 20ms apart. At the moment I am using busy waiting in a separate thread, but I am worried about the CPU overload. Example : while True: if...

performance issues executing list of stored procedures


c#,multithreading,performance,loops
I'm having some performance issues when starting my windows service, the first round my lstSps is long (about 130 stored procedures). Is there anyway to speed this up (except for speeding the stored procedures up)? When the foreach is over and goes over to the second round it goes faster,...

How can we make a thread to sleep for a infinite time in java?


java,multithreading,thread-sleep
Pls help me to understand how can we make a thread to sleep for a infinite time period .

Run class methods in different threads


java,multithreading,object,methods
Let's suppose I have this class: public class Myclass { method1(); method2(); method3(); } I want to know if there's a way to run all 3 methods in different threads simultaneously. Is there a way to create a class MyThread : public class MyThread{ //implementation } in way that it...

c - Parallelising a function


c,multithreading,table,rainbowtable
I'm trying to implement parallelism to this function I want it to take as many threads as possible, and write the results to a file. The results need to be written in the file in the incrementing order so the first result needs to be written first the second second...

Calling dispatch_sync from a concurrent queue - does it block entirely?


ios,objective-c,multithreading,swift,grand-central-dispatch
Let's say I hypothetically call a dispatch_sync from a concurrent queue - does it block the entire queue or just that thread of execution?

Crystal convert the idea behind Thread pool to Fibers/spawn


multithreading,coroutine,crystal-lang
I'm having some hard time learning the idea behind Fibers\coroutines and the implementation in Crystal. I hope this is the right place to ask this, I'll totally accept a "not here" answer :) This is my usual way of handling multi-threading in Ruby: threads = [] max_threads = 10 loop...

Difference between thread.join and thread.abort in python multithreading


python,multithreading
I am new to python multi threading and trying to understand the basic difference between joining multiple worker threads and calling abort on them after I am done processing with them. Can somebody please explain me with an example?

wait for an event regulary


multithreading,events
In a program I need to wait for an event (keypress) and get it's char. after that program will continue. this progress will Repeat several time. in my first try, codes run and any character did not save. I find out I should use threading but I am not Familiar...

Any way to catch an exception occurring on a thread I don't own?


c#,multithreading,exception
I'm using a crappy third party library because unfortunately I have no choice. This library creates a bunch of threads internally when I call it, and occasionally throws a NullReferenceException on one of these threads. Is there any way for me to catch these exceptions even though I don't own...

Show imageview after click wait a moment then hide again [Android]


android,multithreading,imageview,show-hide
I'm trying to show some imageviews after the user has clicked on a button then wait for some time for the user to see which was the correct button to click then hide it again. Something like this: User clicks on button giving his answer -> Score is updated and...

Web API - Set each thread with the HttpRequestMessage id?


c#,.net,multithreading,task-parallel-library,web-api
I have a web api coded in c#. The web api uses functionality which is shared with other in-house components. it depends on single threaded flows and uses thread local storage to store objects, and session information. Please don't say if it's good or bad, that's what I have to...

Interleaving processes on two threads


c#,multithreading,synchronization
I have a library that I can use to access some tabular data. This library is the only way I have of accessing the data. The method I am using takes a query string and a callback that is called for each result row. Currently, the callback loads each row...

Guarantee TransformBlock output sequence


c#,multithreading,async-await,task-parallel-library,tpl-dataflow
From the TPL documentation As with ActionBlock<TInput>, TransformBlock<TInput,TOutput> defaults to processing one message at a time, maintaining strict FIFO ordering. However, in a multi-threaded scenario, i.e. if multiple threads are "simultaneously" doing SendAsync and then "awaiting" for a result by calling ReceiveAsync, how do we guarantee that the thread that...

EntityFramework 6 / SqlCe 4 SaveChangesAsync()


c#,wpf,multithreading,entity-framework,sqlce
I have the following method running in a non-GUI thread within my application: private async Task PerformContextSubmitAsync() { try { await DataContextProvider.GetDefaultContext().SaveChangesAsync(); } catch (Exception ex) { Log.Error("Error performing context submit", ex); } } Which is called like this: await PerformContextSubmitAsync(); The application is a WPF/Prism based application so I'm...

Interaction with user on Thread cause my app crash [duplicate]


android,multithreading,java-threads
This question already has an answer here: Android “Only the original thread that created a view hierarchy can touch its views.” 9 answers My app crashes if TextView.setText is inside Thread: NOTE: The following class is inside of MainActivity. private class StreamThread extends Thread { public StreamThread() { }...

std::condition_variable – notify once but wait thread wakened twice


c++,multithreading
Here's a simple C++ thread pool implementation. It's an altered version orginated from https://github.com/progschj/ThreadPool. #ifndef __THREAD_POOL_H__ #define __THREAD_POOL_H__ #include <vector> #include <queue> #include <memory> #include <thread> #include <chrono> #include <mutex> #include <condition_variable> #include <future> #include <functional> #include <stdexcept> namespace ThreadPool { class FixedThreadPool { public: FixedThreadPool(size_t); template<class F, class......

Does wait() need synchronization on local variable


java,multithreading,synchronization
I had this code (which was working fine): public static void runOnUiThread(Activity c, final Runnable action) { // Check if we are on the UI Thread if (Looper.getMainLooper() == Looper.myLooper()) { // If we are, execute immediately action.run(); return; } // Else run the runnable on the UI Thread and...

What happens if all node.js's worker threads are busy


javascript,node.js,multithreading
I try to understand how node.js works and although I have read this article: When is the thread pool used? I am not sure what happens if all worker threads are busy and another async I/O operation is ready to be executed. If I got this http://www.future-processing.pl/blog/on-problems-with-threads-in-node-js/ article right, the...

Opening facebook in a panel of winforms


c#,multithreading,facebook,panel,process.start
I am in need to open facebook(whatsapp,skype etc) with in a panel. please suggest something to achieve the same. I working on windows 7. If facebook is not possible then please suggest with whatever the task is possible whether with facebook messenger,whatsapp (site or app),skype or any other social networking...

Multiple Threads searching on same folder at same time


c#,multithreading,file-search
Currently I have a .txt file of about 170,000 jpg file names and I read them all into a List (fileNames). I want to search ONE folder (this folder has sub-folders) to check if each file in fileNames exists in this folder and if it does, copy it to a...

How does the kernel separate threads from processes


linux,multithreading,linux-kernel
Suppose I have a browser process like Firefox, that has pid = 123. Firefox has 5 opened tabs each running in a separate thread, so in total it has 5 threads. So I want to know in depth, how the kernel will separate the process into the thread to execute...

Sequential file IO from different threads fail with FileSystemException


java,multithreading,windows-7,io
I am trying to see how fast i can do something like: write a small file rename it delete it This basically looks like: import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class QuickIO { public static void main(String[] args) throws IOException { Path fileToWriteTo = Paths.get("C:\\Temp\\somefile.txt"); Path fileToMoveTo...

Simple thread/mutex test application is crashing


c++,multithreading,c++11,mutex,mingw-w64
I wrote a simple test program which accumulates random samples to a buffer using multiple threads. Each thread uses a stack for reducing the mutex waits. This is for investigating problems in a much larger program. The code currently crashes on mingw-w64 4.9.2 Any idea why? Debugging halts on "signal-received"...

Java 5 Multi threading, catch thread exceptions


java,multithreading,exception,concurrency,java-5
I've got a class that generates threads (file i/o). I need to catch exceptions in the thread - I don't want to do anything fancy, I want to kill the main thread, rather, stop processing altogether so it can start over. If I catch the exceptions in the thread, that's...

Looking to pause a thread using thread.sleep


java,multithreading
I am using a mouse listener for mouse pressed and released. When the mouse is pressed I want to have a counter incrementing a variable, and when the mouse is released I want to decrement that variable. Right now, my code is working and does that but the increment is...