Basic tutorial for multithreading

I'm a coding newbie, but I really wanna learn how to do multithreading and event handling. Does anyone know of any good tutorials out there, or can they explain it to me in a nutshell?

Multithreading Find how many threads other users are using on a UNIX system

So I have some computationally heavy code that can happily chug along using 32 threads or more efficiently. I also have access to a cluster through my school that has 32 processor cores. "Sweet!" you might say. But, alas, the code gets very unhappy if you don't have each thread paired in a dedicated way to a processor. For the numerically inclined, my BLAS implementation takes major hits to efficiency if the thread it's running on gets swapped out for another. This wouldn't be an issue, excep

Multithreading Threads and processes?

In computer science, a thread of execution is the smallest unit of processing that can be scheduled by an operating system. This is very abstract! What would be real world/tangible/physical interpretation of threads? How could I tell if an application (by looking at its code) is a single threaded or multi threaded? Are there any benefits in making an application multi threaded? In which cases could one do that? Is there anything like multi process application too? Is technology a limiting fact

Multithreading How to decrease thread pool size value using ThreadPoolExecutor?

I set CorePoolSize to 10 and MaximumPoolSize to Integer.MAX_VALUE . now i increased CorePoolSize to 15 and getPoolSize() showed 15 threads. After this i decreased CorePoolSize to again 10 , this time getPoolSize() is showing 15. And 15 threads are running. I only want number of threads in threadpool as CorePoolSize and i don't want to change MaximumPoolSize value. I also don't want to fix CorePoolSize. How this can be possible?

Multithreading Managing dynamic number of threads

First of all, I'm still familiarizing myself with multi-threading, and don't know much terminology. I need to make sure I'm doing this right, because it's a sensitive subject. Specifications What I'm building is a component which will contain a dynamic number of threads. Each of these threads is re-used for performing a number of requests. I can provide all necessary details to the thread as I create it and before I execute it, as well as provide event handlers. Once it's executed, I'm pretty

Multithreading How to list and kill threads/processes in Perl without using external command(s)?

I need to kill some processes and threads (if exist) in Perl application, but I don't want to use external command(s) such as ps, grep, awk, cut, uniq or kill. My current code is: my $appName = $0; $appName =~ s/^.*\/([^\/]*)$/$1/; $_ = qx(kill -9 `ps -eLao pid,command | grep '$appName\[ 0-9\]*\$' | grep -v grep | awk '\$1 != $$' | cut -d' ' -f1 | uniq` 2>&1); I am using VPS, so my memory is limited. The code above sometimes returns undef, as system can

Multithreading omp flush and cc-NUMA architecture

there is something that I miss about the cc-NUMA architecture and the need to flush variables. We all know that if two threads modify the same cache line then a "false sharing" condition will rise forcing the cache lines to be reloaded again. So why we need to flush variables in order to make thread exchange information? Suppose that in the serial region you declare : int flag=0; And then in parallel region Thread 0 assigns the shared variable: flag=1; will Thread 1: while (!flag){}

Multithreading How to get the html contents of millions urls links

Given a url link, I want to get the contents of the page in html format .In Java,I know that I can implement this with getInputStream method. Question is that, now I have millions of URLs. And want to get the html pages of them. If I still use the getInputStream. It is time-consuming and the performance is bad. So I want to speed up the fetch page process. Hope to get efficient method and high speed to do this. Thanks in advance!

Multithreading Testing a Multithreaded UDP Server (Java)

I am implementing a multithreaded UDP client-server dictionary. I think I have implemented it correctly but I don't know how to test it properly. If anyone has the time, can you kindly have a quick look at my code? This is how I usually run my program: java DictServer <port> <dictionary file name> java DictClient localhost <port> <word to search> This the output of the server (client has been run 3 times here): Server Started Number of threads active: 1 Number of th

Multithreading how can I kill or pause a thread when it return to previous intent or home page

There is a Button that start an activity every 30 second by a thread. My problem is when I start the activity I cannot cancel or pause it and it runs periodically when I go back to the previous page or even home screen and show the Intent. ans also when I come back and change some setting like loop duration and press the Button, the new thread is added to previous one and both run with their loop time. I tried to use finish() in onPause() or interrupt but I could not solve the problem! Threa

Multithreading Perl Module ForkManager not working

My error is as follows Cannot start another process while you are in the child process at /usr/lib/perl5/site_perl/5.8.6/Parallel/ForkManager.pm line 463. The part of my code that is having issues is below, below my code is the sub routine thats failing in forkmanager, I cannot figure out why. Without forkmanager I can run just fine. my $pm = new Parallel::ForkManager($MAX_PROCESSES); for (0..$SCOUNT) { my $pid = $pm->start and next; my %shash = (); %shash = ( ID => "

Multithreading What is the correct way to implement concurrency in wcf service?

I am trying understand concurrency in wcf and downloaded a sample code from here and done some changes for testing two way calls. To my surprise I could not see the effect of concurrency for two way calls (Although I can see concurrency for one way calls). Is it the way WCF concurrency model works? (or) Am I doing something terribly wrong? This is the service code. [ServiceContract] public interface IHelloWorldService { [OperationContract(IsOneWay=true)] void Call(string ClientName);

Multithreading Fast producer and slow consumer

I have a use case where a fast producer inserts data in a queue and a slow consumer consumes data. The problem I'm facing is continuous increase in queue size over time. I have a class implementation where a std::queue is protected by mutex and condition variable for concurrent reads and writes. How can this adapted to case where the producer after reaching a MAX_THRESHOLD till stop inserting data into the queue and the consumer has consumed some amount of data signals the producer to insert d

Multithreading WSAsend to all connected socket in multithreaded iocp server

I work on IOCP Server (Overlapped I/O , 4 threads, CreateIoCompletionPort, GetQueuedCompletionStatus, WSASend etc). I also created an auto-reset event and put the handle in the OVERLAPPED structure for each asynchronous I/O operations. And the question is: How to send buffer too all connected sockets properly? Each socket is stored in linked list of context info structures. I'm not sure is that approach below is ok? ... DWORD WINAPI WorkerThread() { // 1 of 4 workthread ... GetQueuedCompletio

Multithreading PowerShell Write to Same File Multiple Jobs

I have a script that pulls one line of data from a file on multiple servers. I have a single-threaded version that works just fine, but I want to get it to run faster. Since I only need one line of one file from each server, I'm sure I could run this in parallel. I pulled code from multiple places to get a multi-threaded script running, but when I try to get all the results to print to one output file, nothing prints. I wonder if anyone can look at my code to tell me why this same script, withou

Multithreading Exception while accessing a shared EXE by multiple threads

I have a requirement where I need to spawn multiple threads to execute a process. here the process is an exe. I'm facing a problem while multiple threads try to access the exe which is in a shared path. I tried using a lock .even that din't help. Any help appreciated.Please find the code below. Task t; t = Task.Factory.StartNew(() => { //lock (thisLock) //{ // process = ProcessHelper.StartNew(objPSI.FileName, objPSI.A

Multithreading Running an infinite loop in a JavaFX(Embedded in javax.swing.JFrame) App

I am trying to run an Infinite loop in my JavaFX app. An infinite while loop is present in my code in the Kulta.java file. This loop actually freezes my app. While the same thing works when I port the app to normal javax.swing. Now since java.lang.Thread doesn't work for javafx, I came accross javafx.concurrent.Task, which is not working as intended. As one of the main features of multithreading, i.e. running an infinite loop in a GUI app, is not served properly, please help me with the solution

Multithreading Reg multiple synchronised block with multiple JVM's

I have a java application deployed on WAS.It receives request from WPS(Websphere Process Server) and inserts the data into Oracle DB. Inorder to avoid multithreading issues,I wrote the code in a synchronised block.Now the application is working fine on Dev env(single JVM). I came to know that QA has multiple JVM's. I heared that synchronised block doesn't work on multiple JVM's,so I am worried whether my application works in QA env?

Multithreading Utilize Results from Synchronized Hashtable (Runspacepool 6000+ clients)

Adapting a script to do multiple functions, starting with test-connection to gather data, will be hitting 6000+ machines so I am using RunspacePools adapted from the below site; http://learn-powershell.net/2013/04/19/sharing-variables-and-live-objects-between-powershell-runspaces/ The data comes out as below, I would like to get it sorted into an array (I think that's the terminology), so I can sort the data via results. This will be adapted to multiple other functions pulling anything from Se

How to get started multithreading in Perl

I have a perl program that takes over 13 hours to run. I think it could benefit from introducing multithreading but I have never done this before and I'm at a loss as to how to begin. Here is my situation: I have a directory of hundreds of text files. I loop through every file in the directory using a basic for loop and do some processing (text processing on the file itself, calling an outside program on the file, and compressing it). When complete I move on to the next file. I continue t

Multithreading Tomcat JSP:How to laod multiple JSP file in one go

I need to execute multiple DIV on JSP parallel/concurrently. There is 6 DIVS, each DIV fire some http request to server. Now there is requirement to excute set of request in parallel. e.g There is A.jsp which contains DIV A, DIV B, DIV C, DIV D. Now I want load all four div to execute at a time parallel while loading of A.jsp. Right now it's executing sequentially.

Multithreading Read a variable in another thread

I'm using linux and I have two variable that is read/write in another thread. Once in a while (100ms) ThreadB reads the status of the variables and does something. It's basically a while(1){ dosomething(); usleep(); }. I'm worried the variables will be cached and never updated. What's the best way to ensure the loop will work after optimizations? I am thinking volatile should do the job but I hear it doesn't work sometimes. Both loops don't run frequently (10ms+). What's the most simple and str

Multithreading High Availability - What does Crossover mean in this context?

I'm working on a Mesos framework to run some jobs and it seems like a great opportunity to learn about making a highly available system. To that end, I'm doing some reading on distributed systems and I made the mistake of visiting wikipedia. The passage in question is talking about a principle of HA engineering: Reliable crossover. In multithreaded systems, the crossover point itself tends to become a single point of failure. High availability engineering must provide for reliable

Multithreading Delphi : How to create and use Thread locally?

My database is in a VPS and I should get some query from my tables Because of getting query from server taking long time ( depending on Internet speed ! ) , I want to use threads to get queries Now I create a thread and get query and then send result to my forms with sending and handling messages I want to know is it possible to create and use a thread locally ?!? My mean is : procedure Requery; var ... begin Create Thread; ... Pass my Query Component to Thread ... Getting Query in

Multithreading Can Akka or the Actor model give more processing power to an app?

I’m trying to get my head around why use Akka/Actor model. Suppose a machine has allocated to my stateless application only 2 threads and I have two Actors (Actor1 & Actor2). When a requests comes to Actor1 it pushes it onto Actor2, freeing up Actor1 to serve more requests. In this case at least 1 thread is always occupied, either by Actor1 or Actor2. Why shouldn’t I just serve requests coming into the Actor1 onto the Actor2 in a single thread (blocking way) which will also use 1 thread an

Multithreading Javafx Task<ObserveableList>.updateValue only fires first change event

I'd like to observe a task's valueProperty, and take action when it's changed by updateValue(). The change event only seems to get fired on the first update though. Oracle's getValue document has a section implying that it's kosher to repeatedly call UpdateValue to return partial results. Perhaps I'm not understanding what they mean by "updates are coalesced". Minimum Example import javafx.application.Application; import javafx.application.Platform; import javafx.beans.property.ReadOnlyOb

Multithreading Why not to use mutex inside an interrupt

i have passed through this post and i noticed that in Clifford's answer he said that we shouldn't use mutex in an interrupt, i know that in an interrupt we have to avoid too much instructions and delays ext... but am not very clear about the reasons could anyone clarify me for which reason we have to avoid this? In case that we want establish a synchronous communication between 2 interrupt driven threads what are the other mecahnism to use if using mutex is not allowed?

Multithreading PyQt: How to send a stop signal into a thread where an object is running a conditioned while loop?

I'm doing some multi-threading. I have a worker class with a work method, which I send into a separate QThread. The work method has a conditioned while loop inside. I want to be able to send a signal to the worker object to stop it (changing the _running condition to false). This will cause the while loop to exit, and a finished signal to be sent from the worker object (which is connected to the quit slot of the worker's thread). The false condition is sent to the worker object via a signal, bu

Multithreading missed signal in c++11 condition variable

I have a small doubt about thread being woken up and unavailability of the lock std::mutex mut; std::queue<data_chunk> data_queue; std::condition_variable data_cond; void data_preparation_thread() { while(more_data_to_prepare()) { data_chunk const data=prepare_data(); std::lock_guard<std::mutex> lk(mut); data_queue.push(data); data_cond.notify_one(); //mutex is still locked here

Multithreading Delphi queue and synchronize parameters

I have posted a question that confused me about the multi threading and I haven't found an answer online. Let's say that I have created something like TTest = class(TThread) and so you can imagine that I have an Execute. Inside it I can call: Synchronize(procedure begin //code end); Queue(procedure begin //code end); From what I have understood the code above should have another hidden parameter before the anonymous m

Multithreading Python 3.4 Comms Stream Delegate - Non-blocking recv and send - data out from asyncio

I'm putting together a client server app on RPi. It has a main thread which creates a comms thread to talk to an iOS device. The main thread creates an asyncio event loop and a sendQ and a recvQ and passes them as args to the commsDelegate main method in the comms thread. The trouble I'm having is when iOS device connects, it needs to receive unsolicited data from this Python app as soon as the data becomes available and it needs to be able to send data up to the Python app. So send and recei

Multithreading Jmeter Multiple Running Thread Group

Is there a property file in Jmeter that configures how many thread groups can run concurrently. I have a test case where if I run 5 thread groups, the test is successful but the moment I add a 6th thread group, one of the thread group fails. Is there a limit to no of thread groups we can run concurrently.

Multithreading Sidekiq running multiple jobs in a single heroku dyno?

I have noticed that on some of my sidekiq workers, they appear to be running multiple processes (Working multiple jobs concurrently) in a single dyno (The logs would suggest this). How many processes could be/are running separate jobs within a single dyno concurrently without using swarming (The enterprise feature)? I have everything set up to defaults without using swarms, so each sidekiq worker is using 25 threads. What exactly all these threads are used for, however, I have no idea. Can any

Multithreading Task executor not stopping

In my code: spring-integration, a scatter gather channel is there and the scatter channel using a task-executor to call two micro-services parallely and gather the response in gather channel. I used logger channel to log request response in the scatter gather channel. I can see the response from two services came to gather channel but stuck there not going to next channel. I suspected release strategy of gather channel may not working but same is working if I don't use thread(task executor). Sug

In C++ multithreading applications, should I pass lambda or function with parameters?

I have just started learning about multithreading in C++... is there a difference between t1 and t2? #include <iostream> #include <thread> #include <mutex> std::mutex mutexCout; //prints the value of x, and then increments it //param: int value to display and increment void foo (int& x) { std::lock_guard<std::mutex> guard_(mutexCout); std::cout << "x is " << x << "\n"; ++x; } //testing different ways to call a function with reference

writing tfrecord with multithreading is not fast as expected

Tried to write tfrecord w/ and w/o multithreading, and found the speed difference is not much (w/ 4 threads: 434 seconds; w/o multithread 590 seconds). Not sure if I used it correctly. Is there any better way to write tfrecord faster? import tensorflow as tf import numpy as np import threading import time def generate_data(shape=[15,28,60,1]): return np.random.uniform(size=shape) def _bytes_feature(value): return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))

Multithreading AWS S3 File Sync

I am trying to do file syncing from local source to a S3 bucket where I am uploading the files to S3 bucket by calculating MD5 checksum and putting it in the metadata for each file. The issue is that while doing so I also checked the files which are already there at destination to avoid duplicate upload. This I do by creating a list of files for upload which doesn't match on name and MD5 both. This operation of fetching the metadata for S3 files and computing MD5 for local files on the fly and t

Multithreading How can I wait for an (audio play) command to finish before executing the next one, in Octave?

I'm running the following simple audio playing script that plays some white noise, using 2 different methods. However, unless I put the pause (T+1) after the first play command, the second one (seem to be?) is executed at the same time. fs = 44100; % sampling frequency, Hz T = 5; % signal duration, s N = round(fs*T); % number of samples % use rand to create noise, wave is then normalized to a max of 1: wave = 2*(rand(N,1)-0.5); wave = wave./max(abs(wave)); disp ("Now

Multithreading How do I share a private variable among tasks in Flink (Scala)?

I want to share a private variable in my Flink job (Scala) across the parallel tasks of Flink. My code is something like this : object myJob extends flinkJob { private val myVariable = someValue def run(params) : Unit = { //Stream processing //myVariable is used here in the ProcessFunction } } When I run this job with some parallelization, will there be a single copy of "myVariable" shared across all of the Flink tasks? If not, how can I ensure that only one single copy of the variabl

How to implement multithreading in wasm created using golang?

I am working on a javascript project which initially had all complex logic written in JS. However it was very slow so we had ported all the complex logic to golang now due to architectural constraints we cannot call APIs of the golang, so we moved towards wasm where you build your golang code into a wasm file and call it from your js code and hence eliminating API calls. Now everything was working fine until we have received some complex object which takes a lot of time if you execute through w

Multithreading Why C++ thread calls destructor multiple times?

I am curious why a simple c++ program like the one attached below calls destructor of the work1 object multiple times while it is being processed in std::thread. Why is that it calls destructor multiple times. class work1 { public: work1(int x_) : x(x_) { ++count; std::cout<<"\n[WORKER1] Ctor : "<<count<<std::endl; } ~work1() { std::cout<<"\n[WORKER1] Dtor : "<<count<<std::endl; } void operator() () {

Multithreading Threads are freezing main form

I want to run multiple thread. Each thread should convert JPEG to Bitmap. Conversion works but my whole application is always using 12%-13% of CPU. I have an 8 core CPU so it seems the whole application uses just a single core. Also while the threads are working the main form is frozen and doesn't respond. unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Jpeg, Dialogs, StdCtrls; type TForm1 = class(TForm) Button1: TButton; pr

Multithreading How to speed up writing points to InfluxDB?

I'm writing points (60k per batch) to InfluxDB. Point contains time (i64) and value (f64). It looks like. use influx_db_client::{ Client, Point, Points, Value, Precision }; use tokio; fn main() { let client = Client::new(Url::parse("http://localhost:8086").expect("Cannot parse url"), "test"); let data: Vec<Point> = get_data(); tokio::runtime::Runtime::new().unwrap().block_on(async move { for chunk in data.chunks(60000) { let points = Points::crea

Multithreading APScheduler Threading design pattern

I'm currently writing an application to schedule some metrics with APScheduler (3.6.0) and python3.6 After 5-6 days running, the scheduler stops without any error. So I thought it could be a ressource / concurrency problem. I have different schedules like every 15 minutes, every 30 minutes, every hour etc... My Scheduler is initilized as following and I am only using threads right now : executors = { 'default': ThreadPoolExecutor(60), 'processpool': ProcessPoolExecutor(5) } schedule

Multithreading TThread.OnTerminate executing thread

The Delphi help for TThread.OnTerminate states that: The method assigned to the OnTerminate event is executed in the context of the main thread rather than the context of the thread being terminated. Is this even the case when the thread is created in another thread than the main thread? So, is the OnTerminate called in the thread that created the TThread, or is it called in main thread? The IDE does not tells me this. When I debug, I see no active thread in the OnTerminate event. :-/

  1    2   3   4   5   6  ... 下一页 最后一页 共 59 页