FAQ Database Discussion Community


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

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

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?

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

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

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

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?

Error When Testing threading Module

python,multithreading
I am looking to implement the threading module (python3), and wanted to test it out first to see how it could help reduce runtime. The following code does not implement multithreading: import threading, time import queue q = queue.Queue(10000000) def fill_list(): global q while True: q.put(1) if q.qsize() == 10000000:...

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

Double free or corruption (out) on return

c++,multithreading
I'm doing an assignment that involves calculating pi with threads. I've done this using mutex and it works fine, but I would like to get this version working as well. Here is my code. #include <iostream> #include <stdlib.h> #include <iomanip> #include <vector> #include <pthread.h> using namespace std; typedef struct{ int...

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

C# Timer refuses to stop ticking

c#,multithreading,timer
I have been scratching my head all day on this one and it is infuriating me, is there any obvious problems with this that I do not know about ? Here is the code: private Timer _timer = null; private EventHandler ev = null; private void startAnimatingPicStatus() { Console.WriteLine(" |...

C# Thread Abort safety

c#,multithreading
Using SqlDataSourceEnumerator.Instance.GetDataSources(); Within a running thread, is it safe to call thread.Abort() while that is still running to kill the process? Note: That's a thread within a background worker. I need to be able to cancel the background worker, but can't if that one line is blocking...

Trying to understand synchronized methods

java,multithreading
For the code below, the expected output is: Waiting for b to complete... Total is: 4950 How come it can't print the Total is.. first then Waiting for b.. after? I'd think b.start() could be executed first in some cases, then it holds onto ThreadB's lock with synchronized(this) in ThreadB.run()...

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

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

Are the LAPACK routines thread safe?

multithreading,fortran,lapack,blas
I am a novice using the LAPACK routines, so I don't deeply know them, and I want to use them in parallelized loops (openmp). I use Ubuntu 14.04LTS and have LAPACK installed using my package manager. The version installed is: liblapack3 3.5.0-2ubuntu1 Library of linear algebra routines 3 - shared...

Location Manager - requestLocationUpdates crashes

android,multithreading,gps,geolocation
I am trying to fetch current user location - city, using the code below : private String getCurrentLocation() { LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); LocationListener locListener = new MyLocationListener(); try { gps_enabled = locManager .isProviderEnabled(LocationManager.GPS_PROVIDER); } catch (Exception ex) { } try { network_enabled = locManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); } catch (Exception...

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

Thread interrupt not working (Java Android)

java,android,multithreading,interrupted-exception
Edit: see here! I have a thread with the Runnable shown below. There is a problem with it which I can't figure out: half of the times I call interrupt() on the thread (to stop it) it does not actually terminate (the InterruptedException is not catched). private class DataRunnable implements...

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

How to ask the GUI thread to create objects?

c#,multithreading,winforms,async-await
I've got the following program flow in my Windows Forms application (WPF is not a viable option unfortunately): The GUI Thread creates a splash screen and a pretty empty main window, both inheriting Form. The splash screen is shown and given to Application.Run(). The splash screen will send an event...

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

Multi producer single consumer queue without dedicated consumer thread

java,multithreading
I'm writing an async application which submits elements to a work queue for processing. The requirements are: There is no background thread listening on the queue. Any thread that submits an element to the queue may be responsible for consuming the queue. There can be multiple concurrent producers, but only...

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

How can I send a function to another thread?

multithreading,unit-testing,rust
I am attempting to write a simpler unit test runner for my Rust project. I have created a TestFixture trait that my test fixture structs will implement, similar to inheriting from the unit test base class in other testing frameworks. The trait is fairly simple. This is my test fixture...

Lock Free Bounded Stack C++11 atomics

c++,multithreading,c++11,stack,lock-free
I was thinking about using very basic bounded (preallocated) stack to keep track of my threads ids in correct LIFO order. So i was wondering if my implementation is thread safe: // we use maximum 8 workers size_t idle_ids_stack[8]; // position current write happening at std::atomic_uint_fast8_t idle_pos(0); // this function...

how to create unkown amount of threads c++

c++,multithreading,client,server
I wrote a server c++ that connect to clients and i want to use thread in order to do some actions and with some clients and not to do only one client finish and go to another client. but i cant create unknown amount of theards only specific. can sombody...

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

Does a class instance thread affinity has any impact on its data?

c++,multithreading,qt
We know from QThread documentation A QObject instance is said to have a thread affinity, or that it lives in a certain thread. When a QObject receives a queued signal or a posted event, the slot or event handler will run in the thread that the object lives in. Does...

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

Unit Testing Synchronous Method With Code Calling Task

c#,.net,multithreading,unit-testing
Given the following class: public class TestAttribute : ActionFilterAttribute { public bool SomeExampleBool = false; public override void OnActionExecuting(HttpActionContext actionContext) { Task.Factory.StartNew(() => { SomeExampleBool = true; }); } } How would you write a valid unit test for OnActionExecuting that Asserts that SomeExampleBool is equal to true? When writing...

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

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.

Difference between String , StringBuilder & StringBuffer?

java,multithreading,thread-safety
I was just going through the net but I could not find a clear & precise difference between String ,StringBuilder & StringBuffer . Please also explain when should we use them and what do we mean by thread-safe in java ? ...

Why JavaFX requires Platform.runLater to change anything in it's UI inside a thread?

java,multithreading,swing,javafx
This code of a simple swing application: final JFrame jFrame = new JFrame(); final JLabel jLabel = new JLabel("Test"); jFrame.add(jLabel); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jFrame.pack(); jFrame.setLocationRelativeTo(null); jFrame.setVisible(true); Thread thread = new Thread(){ @Override public void run() { while(true) { jLabel.setText("Time: " + System.currentTimeMillis()); try { Thread.sleep(1000);} catch(Exception ex) {} } } }; thread.setDaemon(true);...

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

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

How do I restart a scheduled thread if an exception occurs?

java,multithreading
I am running a thread that is scheduled to run every 10 milliseconds with a ScheduledExecutorService. Sometimes the thread fails because of a random uncaught exception, and I wanted to know how to restart the thread when this happens. I tried to make the thread global, and check if the...

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

Is Map enough to be thread safe?

java,multithreading
I have a very simple class: public class IdProvider { private Map<String,AtomicLong> idMap; public IdProvider(){ idMap = new HashMap<>(); } public long getAvailableId(String conversation){ AtomicLong id = idMap.get(conversation); if(id == null){ id = new AtomicLong(0); idMap.put(conversation,id); } return id.getAndIncrement(); } } Different methods asynchronously may pass the same conversation identifier...

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

Issue using std::atomic_flag with worker thread

c++,multithreading,c++11,stdatomic
sorry for the verbosity - I did my best to condense my code sample into a minimally functional class and main() method. I'm trying to use an atomic_flag to notify _rx() within my worker thread to quit when stop() is called. I believe the issue is in trying to create...

Initializing a class using threading (Python)

python,multithreading,class,python-2.7
So I have this code import socket def main(): #does a bunch of argument parsing while True: newsock, fromaddr = s.accept() ssl_sock = context.wrap_socket(newsock, server_side=True) threading.Thread(target=tls_listener, args=(ssl_sock,)).start() def tls_listener(ssl_sock): #the thing I want to turn into a class #calls other functions, does some reporting if __name__ == "__main__": main() I...

UI4J - Thread safe and concurrent use, multiple instances?

java,multithreading,ui4j
Looking at com.ui4j.api.browser.BrowserFactory it appears as if the getBrowser method can only return one instance, as is also documented. This is quite problematic for anyone trying to write some sort of multi threaded crawler, as there will only exists one browser at all times. There is no way to create...

Observing changes in a BlockingCollection without consuming

c#,multithreading,concurrency,producer-consumer,blockingcollection
A consumer thread and multiple producer threads synchronize their work with a System.Collections.Concurrent.BlockingCollection<T>. The producers call blockingCollection.Add() and the consumer runs foreach (var item in blockingCollection.GetConsumingEnumerable()) {...} Now one producer wants to "flush" the buffer: The producer wants to wait until all current items have been consumed. Other producers may...

passing multiple arguments to a threaded function from another class

c++,multithreading
Say I have a class: class This { void that(int a, int b); }; and in my main function I need to start 'that' in a thread, and pass it 2 arguments. This is what I have: void main() { This t; t.that(1,2); //works unthreaded. std::thread test(t.that(1,2)); // Does not...

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

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

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 .

Read lines from file async using WINAPI ReadFile

c++,multithreading,winapi,createfile,overlapped-io
I need to read several lines from file simultaneously, i.e. asynchronously. Lines in file are of the same size. For instance, I need to read the second and the fourth lines of file to separate variables or to an array. I'm more used to c#'s async/await and all these OVERLAPPED...

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

Best, thread safe way to access a field once i.e. for disposal

c#,multithreading,dispose,interlocked
Basically I want to make sure a field in a class (in this case the _changedPoller) is Disposed as early as possible when not needed anymore. I call StopChangedPolling in the class' Dispose method and when certain events occur. What is the best, thread safe way to dispose a field...

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

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

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

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

Trouble getting variable read out of a thread in python

python,multithreading
So I'm trying to write a program that looks for keyboard presses and then does something in the main program based upon what the user inputs. I'm trying to run the keyboard listening in a thread and then compare whats in the variable in my main loop, but I don't...

Communcate with object inside a Task

c#,multithreading,task
I want to know how or even if its required in my case to communicate with an object running inside a Task. I have a collection of processes, which are generic objects that perform some long running monitoring and calculating: private IEnumerable<IService> _services; Since they are based on a common...

problems copying shared hash in perl threads

multithreading,perl
I encountered what I feel is strange behavior of shared hash in perl and needed some help understanding it. The actual problem is in a far larger code-base and I have tried reducing it to smaller reproducible script. So essentially the problem I'm facing is I have a shared variable...

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

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

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

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[]) {...

How to parallelize many (100+) tasks without hitting global GCD limit?

ios,objective-c,multithreading,asynchronous,grand-central-dispatch
The problem: When lazy-loading a list of 100+ icons in the background, I hit the GCD thread limit (64 threads), which causes my app to freeze up with a semaphore_wait_trap on the main thread. I want to restructure my threading code to prevent this from happening, while still loading the...

How to populate concurrenthashmap from multiple threads?

java,multithreading,thread-safety,concurrenthashmap
I have a ConcurrentHashMap which I am populating from multiple threads. private static Map<DataCode, Long> errorMap = new ConcurrentHashMap<DataCode, Long>(); public static void addError(DataCode error) { if (errorMap.keySet().contains(error)) { errorMap.put(error, errorMap.get(error) + 1); } else { errorMap.put(error, 1L); } } My above addError method is called from multiple threads which...

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

How to log an error in the console if one of the callables of the executor service encounter an error

java,multithreading,executorservice
I have a program which uses executorService to which I am passing callables. Each of which is an object of one class which implements java.util.concurrent.Callable. Then the executorService is invoked. A java.lang.NoClassDefFoundError is thrown in the middle of one of the callables in the call() method. However it is not...

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

Using Invoke() to show Form from Threading.Time() thread

c#,.net,multithreading,winforms,.net-3.5
I have the following: public static Form1 MainForm = new Form1(); static ManualResetEvent _running = new ManualResetEvent(false); [MTAThread] private static void Main() { int startin = 60 - DateTime.Now.Second; var t = new System.Threading.Timer(o => Analyze(), null, startin*1000, 60000); _running.WaitOne(); } public static void Analyze() { Action a = new...

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

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

Thread joining using a destructor

c++,multithreading,destructor
This is a continuation to my question: Thread creation inside constructor Now that I have successfully created a thread in a constructor, I know that it must be joined. As I am developing an API, I have no control over the main function so I can't join it there. Will...

Run multiple request from Action and wait till one ends

c#,multithreading,web-api
I have web api 2.1 service. Here is my Action : public IHttpActionResult Get() { // Desired functionality : // make e.g 5 request to `CheckSomething` with different parameter asynchronously/parallel and if any of them returns status Ok end request and return its result as result of `Get` action; }...

Don't execute the thread when Thread is already running

c#,multithreading
I have a Thread to export date into Excel. But when i run the Thread for the second time it may not execute.. My code: if (Thread.CurrentThread == null || Thread.CurrentThread.ThreadState == System.Threading.ThreadState.Stopped) { new Thread(() => { Thread.CurrentThread.Name = "Export to Excel Thread"; Thread.CurrentThread.IsBackground = true; //Code to export...

Is there an equivalent of Java 'volatile' in C++?

java,c++,windows,multithreading
In Java, sometimes when accessing the same variable from different threads, each thread will create its own copy of the variable, and so if I set the value of the variable in one thread to 10 and then I tried to read the value of this variable from another thread,...

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

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

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

Potential race condition in the timer class?

java,multithreading,timer,thread-safety
I have written a timer which will measure the performance of a particular code in any multithreaded application. In the below timer, it will also populate the map with how many calls took x milliseconds. I will use this map as part of my histogram to do further analysis, like...

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

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

Popen.subprocess in threads

python,multithreading,sockets,popen
I have a client server code in python, wherein the client queries the server about a process running on the server and provides the memory threshold. If the process consumes more memory than the threshold,the server kills the process and restarts it. The problem is since I am creating a...

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

Designing a multi-thread matrix in Java

java,multithreading
I have a matrix that implements John Conway's life simulator in which every cell represents either life or lack of it. Every life cycle follows these rules: Any live cell with fewer than two live neighbors dies, as if caused by under-population. Any live cell with two or three live...

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

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

Condition variable's notification is missed

c++,multithreading,condition-variable
At the moment I am writing some kind of Fork/Join pattern using std::threads. Therefore I wrote a wrapper class for std::thread which uses a reference counter for all children. Whenever a child finishes its execution the reference counter is decremented and a notification is sent to all waiting threads. The...

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

Upload multiple photos to SFTP in Async

android,multithreading,android-asynctask,ftp,sftp
I want to upload multiple photos to SFTP server but with the following code only one photo is uploaded. Please anybody has any idea where I m getting wrong or have a better approach for this private class uploadFileOnFTPServerAsync extends AsyncTask<Void, Void, Void> { ProgressDialog pdDialog; @Override protected void onPreExecute()...

Socket don't save values in list

java,multithreading,sockets,arraylist
I'm new in network developing in Java and I want to create a simple Socket server, that get values from client and collects all of them in ArrayList. I wrote an example code, but in server side it not collecting the strings. This is my server side: Server public class...

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

Sharing data between multiple java threads and get the updated value

java,multithreading,thread-safety
I want to create a java application , where we want to make rest calls for multiple users , with the help of an access token. I am using 1 thread per user . The access token, that I am using , is valid for 1 hour.Once the token expires...

unable to change a label text from NetworkAddressChangedEventHandler c#

c#,multithreading,visual-studio-2010
i will start with saying that i don't know c# very good and it's probable a very simple solution. what i want to achieve is when network status is changed i want to change a label i found out how to triger and event when network is changed using System.Net.NetworkInformation;...

JavaFX splash screen message and progress not updating

java,multithreading,javafx
I have a JavaFX application that checks for the presence of a database at startup. If the database is not found, a "seed" database must be created before the program can proceed. Since creating the seed database can be lengthy, I want to display a splash screen and show progress...

I'm getting exception Cross-thread operation since i'm using ui var in a thread operation how should i handle it? [duplicate]

c#,.net,multithreading,winforms
This question already has an answer here: Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on 12 answers I have this progress changed event: private void videosInsertRequest_ProgressChanged(IUploadProgress obj) { toolStripStatusLabel1.Text = obj.Status.ToString(); } And also this event: private void videosInsertRequest_ResponseReceived(Video obj)...

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

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

How to add system time(running) to a Jpanel?

java,multithreading,swing
I am quite new to java coding. So don't know much of it. I am trying to add system clock(running) to my frame. I am using a jpanel to do so. Here is my code, import javax.swing.*; import java.util.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Emp_Try implements ActionListener,...