Search Results

Search found 1638 results on 66 pages for 'multithreading'.

Page 13/66 | < Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >

  • java: communication between threads

    - by TRU7H
    I'm making a little java game in which I would have two threads (well as the FIRST step towards multithreading...), one for the logic and one for the drawing. So my question is: How can I make those two communicating which each other? Requirements: accessing variables and object from a another thread syncing them so they each complete a same number of "loops" in the same time. (the logic calculates and then the another one draws the results and the loop begins again...) So how is this achievable in java? Thanks in advance!

    Read the article

  • TCP Scanner Python MultiThreaded

    - by user1473508
    I'm trying to build a small tcp scanner for a netmask. The code is as follow: import socket,sys,re,struct from socket import * host = sys.argv[1] def RunScanner(host): s = socket(AF_INET, SOCK_STREAM) s.connect((host,80)) s.settimeout(0.1) String = "GET / HTTP/1.0" s.send(String) data = s.recv(1024) if data: print "host: %s have port 80 open"%(host) Slash = re.search("/", str(host)) if Slash : netR,_,Wholemask = host.partition('/') Wholemask = int(Wholemask) netR = struct.unpack("!L",inet_aton(netR))[0] for host in (inet_ntoa(struct.pack("!L", netR+n)) for n in range(0, 1<<32-Wholemask)): try: print "Doing host",host RunScanner(host) except: pass else: RunScanner(host) To launch : python script.py 10.50.23.0/24 The problem I'm having is that even with a ridiculous low settimeout value set, it takes ages to cover the 255 ip addresses since most of them are not assigned to a machine. How can i make a way faster scanner that wont get stuck if the port is close.MultiThreading ? Thanks !

    Read the article

  • iPhone: how to use performSelector:onThread:withObject:waitUntilDone: method?

    - by Michael Kessler
    Hi all, I am trying to use a separate thread for working with some API. The problem is that I am not able to use performSelector:onThread:withObject:waitUntilDone: method with a thread that I' instantiated for this. My code: @interface MyObject : NSObject { NSThread *_myThread; } @property(nonatomic, retain) NSThread *myThread; @end @implementation MyObject @synthesize myThread = _myThread; - (NSThread *)myThread { if (_myThread == nil) { NSThread *myThreadTemp = [[NSThread alloc] init]; [myThreadTemp start]; self. myThread = myThreadTemp; [myThreadTemp release]; } return _myThread; } - (id)init { if (self = [super init]) { [self performSelector:@selector(privateInit:) onThread:[self myThread] withObject:nil waitUntilDone:NO]; } return self; } - (void)privateInit:(id)object { NSLog(@"MyObject - privateInit start"); } - (void)dealloc { [_myThread release]; _myThread = nil; [super dealloc]; } @end "MyObject - privateInit start" is never printed. What am I missing? I tried to instantiate the thread with target and selector, tried to wait for method execution completion (waitUntilDone:YES). Nothing helps. UPDATE: I don't need this multithreading for separating costly operations to another thread. In this case I could use the performSelectorInBackground as mentioned in few answers. The main reason for this separate thread is the need to perform all the actions in the API (TTS by Loquendo) from one single thread. Meaning that I have to create an instance of the TTS object and call methods on that object from the same thread all the time.

    Read the article

  • C# XMLRPC Multi Threaded newPost something is not right

    - by user1047463
    I recently decided to get my feet wet with c# multi threading and my progress was good until now. My program uses XML-RPC to create new posts on wordpress. When I run my app on the localhost everything works fine and i successfully able to create new posts on wordpress using a multi threaded approach. However when I try to do the same with a wordpress installed on a remote server , new posts won't appear, so when i go to see all posts, the total number of posts remains unchanged. Another thing to note is the function that creates a new post does return the ID of a supposedly created posts. But as I mentioned previously the new posts are not visible when I try to access them in admin menu. Since I'm new to the multithreading I was hoping some of you guys can help me and check if I'm doing anything wrong. Heres the code that creates threads and calls create post function. foreach (DataRow row in dt.Rows) { Thread t = null; t = new Thread(createPost); lock (t) { t.Start(); } } public void createPost() { string postid; try { icp = (IcreatePost)XmlRpcProxyGen.Create(typeof(IcreatePost)); clientProtocol = (XmlRpcClientProtocol)icp; clientProtocol.Url = xmlRpcUrl; postid = icp.NewPost(1, blogLogin, blogPass, newBlogPost, 1); currentThread--; threadCountLabel.Invoke(new MethodInvoker(delegate { threadCountLabel.Text = currentThread.ToString(); })); } catch (Exception ex) { MessageBox.Show( createPost ERROR ->" + ex.Message); } }

    Read the article

  • Thread implemented as a Singleton

    - by rocknroll
    Hi all, I have a commercial application made with C,C++/Qt on Linux platform. The app collects data from different sensors and displays them on GUI. Each of the protocol for interfacing with sensors is implemented using singleton pattern and threads from Qt QThreads class. All the protocols except one work fine. Each protocol's run function for thread has following structure: void <ProtocolClassName>::run() { while(!mStop) //check whether screen is closed or not { mutex.lock() while(!waitcondition.wait(&mutex,5)) { if(mStop) return; } //Code for receiving and processing incoming data mutex.unlock(); } //end while } Hierarchy of GUI. 1.Login screen. 2. Screen of action. When a user logs in from login screen, we enter the action screen where all data is displayed and all the thread's for different sensors start. They wait on mStop variable in idle time and when data arrives they jump to receiving and processing data. Incoming data for the problem protocol is 117 bytes. In the main GUI threads there are timers which when timeout, grab the running instance of protocol using <ProtocolName>::instance() function Check the update variable of singleton class if its true and display the data. When the data display is done they reset the update variable in singleton class to false. The problematic protocol has the update time of 1 sec, which is also the frame rate of protocol. When I comment out the display function it runs fine. But when display is activated the application hangs consistently after 6-7 hours. I have asked this question on many forums but haven't received any worthwhile suggestions. I Hope that here I will get some help. Also, I have read a lot of literature on Singleton, multithreading, and found that people always discourage the use of singletons especially in C++. But in my application I can think of no other design for implementation. Thanks in advance A Hapless programmer

    Read the article

  • Does this use of Monitor.Wait/Pulse have a race condition?

    - by jw
    I have a simple producer/consumer scenario, where there is only ever a single item being produced/consumed. Also, the producer waits for the worker thread to finish before continuing. I realize that kind of obviates the whole point of multithreading, but please just assume it really needs to be this way (: This code doesn't compile, but I hope you get the idea: // m_data is initially null // This could be called by any number of producer threads simultaneously void SetData(object foo) { lock(x) // Line A { assert(m_data == null); m_data = foo; Monitor.Pulse(x) // Line B while(m_data != null) Monitor.Wait(x) // Line C } } // This is only ever called by a single worker thread void UseData() { lock(x) // Line D { while(m_data == null) Monitor.Wait(x) // Line E // here, do something with m_data m_data = null; Monitor.Pulse(x) // Line F } } Here is the situation that I am not sure about: Suppose many threads call SetData() with different inputs. Only one of them will get inside the lock, and the rest will be blocked on Line A. Suppose the one that got inside the lock sets m_data and makes its way to Line C. Question: Could the Wait() on Line C allow another thread at Line A to obtain the lock and overwrite m_data before the worker thread even gets to it? Supposing that doesn't happen, and the worker thread processes the original m_data, and eventually makes its way to Line F, what happens when that Pulse() goes off? Will only the thread waiting on Line C be able to get the lock? Or will it be competing with all the other threads waiting on Line A as well? Essentially, I want to know if Pulse()/Wait() communicate with each other specially "under the hood" or if they are on the same level with lock(). The solution to these problems, if they exist, is obvious of course - just surround SetData() with another lock - say, lock(y). I'm just curious if it's even an issue to begin with.

    Read the article

  • Python MD5 Hash Faster Calculation

    - by balgan
    Hi everyone. I will try my best to explain my problem and my line of thought on how I think I can solve it. I use this code for root, dirs, files in os.walk(downloaddir): for infile in files: f = open(os.path.join(root,infile),'rb') filehash = hashlib.md5() while True: data = f.read(10240) if len(data) == 0: break filehash.update(data) print "FILENAME: " , infile print "FILE HASH: " , filehash.hexdigest() and using start = time.time() elapsed = time.time() - start I measure how long it takes to calculate an hash. Pointing my code to a file with 653megs this is the result: root@Mars:/home/tiago# python algorithm-timer.py FILENAME: freebsd.iso FILE HASH: ace0afedfa7c6e0ad12c77b6652b02ab 12.624 root@Mars:/home/tiago# python algorithm-timer.py FILENAME: freebsd.iso FILE HASH: ace0afedfa7c6e0ad12c77b6652b02ab 12.373 root@Mars:/home/tiago# python algorithm-timer.py FILENAME: freebsd.iso FILE HASH: ace0afedfa7c6e0ad12c77b6652b02ab 12.540 Ok now 12 seconds +- on a 653mb file, my problem is I intend to use this code on a program that will run through multiple files, some of them might be 4/5/6Gb and it will take wayy longer to calculate. What am wondering is if there is a faster way for me to calculate the hash of the file? Maybe by doing some multithreading? I used a another script to check the use of the CPU second by second and I see that my code is only using 1 out of my 2 CPUs and only at 25% max, any way I can change this? Thank you all in advance for the given help.

    Read the article

  • Atomic Instructions and Variable Update visibility

    - by dsimcha
    On most common platforms (the most important being x86; I understand that some platforms have extremely difficult memory models that provide almost no guarantees useful for multithreading, but I don't care about rare counter-examples), is the following code safe? Thread 1: someVariable = doStuff(); atomicSet(stuffDoneFlag, 1); Thread 2: while(!atomicRead(stuffDoneFlag)) {} // Wait for stuffDoneFlag to be set. doMoreStuff(someVariable); Assuming standard, reasonable implementations of atomic ops: Is Thread 1's assignment to someVariable guaranteed to complete before atomicSet() is called? Is Thread 2 guaranteed to see the assignment to someVariable before calling doMoreStuff() provided it reads stuffDoneFlag atomically? Edits: The implementation of atomic ops I'm using contains the x86 LOCK instruction in each operation, if that helps. Assume stuffDoneFlag is properly cleared somehow. How isn't important. This is a very simplified example. I created it this way so that you wouldn't have to understand the whole context of the problem to answer it. I know it's not efficient.

    Read the article

  • C# Multithreaded Domain Design

    - by Thijs Cramer
    Let's say i have a Domain Model that im trying to make compatible with multithreading. The prototype domain is a game domain that consists of Space, SpaceObject, and Location objects. A SpaceObject has the Move method and Asteroid and Ship extend this object with specific properties for the object (Ship has a name and Asteroid has a color) Let's say i want to make the Move method for each object run in a seperate thread. That would be stupid because with 10000 objects, i would have 10000 threads. What would be the best way to seperate the workload between cores/threads? I'm trying to learn the basics of concurrency, and building a small game to prototype a lot of concepts. What i've already done, is build a domain, and a threading model with a timer that launches events based on intervals. If the event occurs i want to update my entire model with the new locations of any SpaceObject. But i don't know how and when to launch new threads with workloads when the event occurs. Some people at work told me that u can't update your core domain multithreaded, because you have to synch everything. But in that case i can't run my game on a dual quadcore server, because it would only use 1 CPU for the hardest tasks. Anyone know what to do here?

    Read the article

  • multi-threaded proxy checker having problems

    - by Paul
    hello everyone, I am trying to create a proxy checker. This is my first attempt at multithreading and it's not going so well, the threads seem to be waiting for one to complete before initializing the next. Imports System.Net Imports System.IO Imports System.Threading Public Class Form1 Public sFileName As String Public srFileReader As System.IO.StreamReader Public sInputLine As String Public Class WebCall Public proxy As String Public htmlout As String Public Sub New(ByVal proxy As String) Me.proxy = proxy End Sub Public Event ThreadComplete(ByVal htmlout As String) Public Sub send() Dim myWebRequest As HttpWebRequest = CType(WebRequest.Create("http://www.myserver.com/ip.php"), HttpWebRequest) myWebRequest.Proxy = New WebProxy(proxy, False) Try Dim myWebResponse As HttpWebResponse = CType(myWebRequest.GetResponse(), HttpWebResponse) Dim loResponseStream As StreamReader = New StreamReader(myWebResponse.GetResponseStream()) htmlout = loResponseStream.ReadToEnd() Debug.WriteLine("Finished - " & htmlout) RaiseEvent ThreadComplete(htmlout) Catch ex As WebException If (ex.Status = WebExceptionStatus.ConnectFailure) Then End If Debug.WriteLine("Failed - " & proxy) End Try End Sub End Class Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim proxy As String Dim webArray As New ArrayList() Dim n As Integer For n = 0 To 2 proxy = srFileReader.ReadLine() webArray.Add(New WebCall(proxy)) Next Dim w As WebCall For Each w In webArray Threading.ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf w.send), w) Next w End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load srFileReader = System.IO.File.OpenText("proxies.txt") End Sub End Class

    Read the article

  • Mutex example / tutorial ?

    - by Nav
    I've noticed that asking questions for the sake of creating a reference list etc. is encouraged in SO. This is one such question, so that anyone Googling for a mutex tutorial will find a good one here. I'm new to multithreading, and was trying to understand how mutexes work. Did a lot of Googling and this is the only decent tutorial I found, but it still left some doubts of how it works because I created my own program and the locking didn't work. One absolutely non-intuitive syntax of the mutex is pthread_mutex_lock( &mutex1 );, where it looks like the mutex is being locked, when what I really want to lock is some other variable. Does this syntax mean that locking a mutex locks a region of code until the mutex is unlocked? Then how do threads know that the region is locked? And isn't such a phenomenon supposed to be called critical section? In short, could you please help with the simplest possible mutex example program and the simplest possible explanation on the logic of how it works? I'm sure this will help plenty of other newbies.

    Read the article

  • Handling user interface in a multi-threaded application (or being forced to have a UI-only main thre

    - by Patrick
    In my application, I have a 'logging' window, which shows all the logging, warnings, errors of the application. Last year my application was still single-threaded so this worked [quite] good. Now I am introducing multithreading. I quickly noticed that it's not a good idea to update the logging window from different threads. Reading some articles on keeping the UI in the main thread, I made a communication buffer, in which the other threads are adding their logging messages, and from which the main thread takes the messages and shows them in the logging window (this is done in the message loop). Now, in a part of my application, the memory usage increases dramatically, because the separate threads are generating lots of logging messages, and the main thread cannot empty the communication buffer quickly enough. After the while the memory decreases again (if the other threads have finished their work and the main thread gradually empties the communication buffer). I solved this problem by having a maximum size on the communication buffer, but then I run into a problem in the following situation: the main thread has to perform a complex action the main thread takes some parts of the action and let's separate threads execute this while the seperate threads are executing their logic, the main thread processes the results from the other threads and continues with its work if the other threads are finished Problem is that in this situation, if the other threads perform logging, there is no UI-message loop, and so the communication buffer is filled, but not emptied. I see two solutions in solving this problem: require the main thread to do regular polling of the communication buffer only performing user interface logic in the main thread (no other logic) I think the second solution seems the best, but this may not that easy to introduce in a big application (in my case it performs mathematical simulations). Are there any other solutions or tips? Or is one of the two proposed the best, easiest, most-pragmatic solution? Thanks, Patrick

    Read the article

  • Achieving Thread-Safety

    - by Smasher
    Question How can I make sure my application is thread-safe? Are their any common practices, testing methods, things to avoid, things to look for? Background I'm currently developing a server application that performs a number of background tasks in different threads and communicates with clients using Indy (using another bunch of automatically generated threads for the communication). Since the application should be highly availabe, a program crash is a very bad thing and I want to make sure that the application is thread-safe. No matter what, from time to time I discover a piece of code that throws an exception that never occured before and in most cases I realize that it is some kind of synchronization bug, where I forgot to synchronize my objects properly. Hence my question concerning best practices, testing of thread-safety and things like that. mghie: Thanks for the answer! I should perhaps be a little bit more precise. Just to be clear, I know about the principles of multithreading, I use synchronization (monitors) throughout my program and I know how to differentiate threading problems from other implementation problems. But nevertheless, I keep forgetting to add proper synchronization from time to time. Just to give an example, I used the RTL sort function in my code. Looked something like FKeyList.Sort (CompareKeysFunc); Turns out, that I had to synchronize FKeyList while sorting. It just don't came to my mind when initially writing that simple line of code. It's these thins I wanna talk about. What are the places where one easily forgets to add synchronization code? How do YOU make sure that you added sync code in all important places?

    Read the article

  • What about race condition in multithreaded reading?

    - by themoob
    Hi, According to an article on IBM.com, "a race condition is a situation in which two or more threads or processes are reading or writing some shared data, and the final result depends on the timing of how the threads are scheduled. Race conditions can lead to unpredictable results and subtle program bugs." . Although the article concerns Java, I have in general been taught the same definition. As far as I know, simple operation of reading from RAM is composed of setting the states of specific input lines (address, read etc.) and reading the states of output lines. This is an operation that obviously cannot be executed simultaneously by two devices and has to be serialized. Now let's suppose we have a situation when a couple of threads access an object in memory. In theory, this access should be serialized in order to prevent race conditions. But e.g. the readers/writers algorithm assumes that an arbitrary number of readers can use the shared memory at the same time. So, the question is: does one have to implement an exclusive lock for read when using multithreading (in WinAPI e.g.)? If not, why? Where is this control implemented - OS, hardware? Best regards, Kuba

    Read the article

  • Python: two loops at once

    - by Stephan Meijer
    I've got a problem: I am new to Python and I want to do multiple loops. I want to run a WebSocket client (Autobahn) and I want to run a loop which shows the filed which are edited in a specific folder (pyinotify or else Watchdog). Both are running forever, Great. Is there a way to run them at once and send a message via the WebSocket connection while I'm running the FileSystemWatcher, like with callbacks, multithreading, multiprocessing or just separate files? factory = WebSocketClientFactory("ws://localhost:8888/ws", debug=False) factory.protocol = self.webSocket connectWS(factory) reactor.run() If we run this, it will have success. But if we run this: factory = WebSocketClientFactory("ws://localhost:8888/ws", debug=False) factory.protocol = self.webSocket connectWS(factory) reactor.run() # Websocket client running now,running the filewatcher wm = pyinotify.WatchManager() mask = pyinotify.IN_DELETE | pyinotify.IN_CREATE # watched events class EventHandler(pyinotify.ProcessEvent): def process_IN_CREATE(self, event): print "Creating:", event.pathname def process_IN_DELETE(self, event): print "Removing:", event.pathname handler = EventHandler() notifier = pyinotify.Notifier(wm, handler) wdd = wm.add_watch('/tmp', mask, rec=True) notifier.loop() This will create 2 loops, but since we already have a loop, the code after 'reactor.run()' will not run at all.. For your information: this project is going to be a sync client. Thanks a lot!

    Read the article

  • Simple POSIX threads question

    - by Andy
    Hi, I have this POSIX thread: void subthread(void) { while(!quit_thread) { // do something ... // don't waste cpu cycles if(!quit_thread) usleep(500); } // free resources ... // tell main thread we're done quit_thread = FALSE; } Now I want to terminate subthread() from my main thread. I've tried the following: quit_thread = TRUE; // wait until subthread() has cleaned its resources while(quit_thread); But it does not work! The while() clause does never exit although my subthread clearly sets quit_thread to FALSE after having freed its resources! If I modify my shutdown code like this: quit_thread = TRUE; // wait until subthread() has cleaned its resources while(quit_thread) usleep(10); Then everything is working fine! Could someone explain to me why the first solution does not work and why the version with usleep(10) suddenly works? I know that this is not a pretty solution. I could use semaphores/signals for this but I'd like to learn something about multithreading, so I'd like to know why my first solution doesn't work. Thanks!

    Read the article

  • synchronize threads - no UI

    - by UshaP
    I'm trying to write multithreading code and facing some synchronization questions. I know there are lots of posts here but I couldn't find anything that fits. I have a System.Timers.Timer that elapsed every 30 seconds it goes to the db and checks if there are any new jobs. If he finds one, he executes the job on the current thread (timer open new thread for every elapsed). While the job is running I need to notify the main thread (where the timer is) about the progress. Notes: I don't have UI so I can't do beginInvoke (or use background thread) as I usually do in winforms. I thought to implement ISynchronizeInvoke on my main class but that looks a little bit overkill (maybe I'm wrong here). I have an event in my job class and the main class register to it and I invoke the event whenever I need but I'm worrying it might cause blocking. Each job can take up to 20 minutes. I can have up to 20 jobs running concurrently. My question is: What is the right way to notify my main thread about any progress in my job thread? Thanks for any help.

    Read the article

  • Parallel doseq for Clojure

    - by andrew cooke
    I haven't used multithreading in Clojure at all so am unsure where to start. I have a doseq whose body can run in parallel. What I'd like is for there always to be 3 threads running (leaving 1 core free) that evaluate the body in parallel until the range is exhausted. There's no shared state, nothing complicated - the equivalent of Python's multiprocessing would be just fine. So something like: (dopar 3 [i (range 100)] ; repeated 100 times in 3 parallel threads... ...) Where should I start looking? Is there a command for this? A standard package? A good reference? So far I have found pmap, and could use that (how do I restrict to 3 at a time? looks like it uses 32 at a time - no, source says 2 + number of processors), but it seems like this is a basic primitive that should already exist somewhere. clarification: I really would like to control the number of threads. I have processes that are long-running and use a fair amount of memory, so creating a large number and hoping things work out OK isn't a good approach (example which uses a significant chunk available mem). update: Starting to write a macro that does this, and I need a semaphore (or a mutex, or an atom i can wait on). Do semaphores exist in Clojure? Or should I use a ThreadPoolExecutor? It seems odd to have to pull so much in from Java - I thought parallel programming in Clojure was supposed to be easy... Maybe I am thinking about this completely the wrong way? Hmmm. Agents?

    Read the article

  • Core Data Errors vs Exceptions Part 3

    - by John Gallagher
    My question is similar to this one. Background I'm creating a large number of objects in a core data store using NSOperations to speed things up. I've followed all the Core Data multithreading rules - I've got a single persistent store coordinator and a managed object context per thread that on save is merging back to the main managed object context. The Problem When the number of threads running at once is more than 1, I get the exception logged on save of my core data store: NSExceptionHandler has recorded the following exception: NSInternalInconsistencyException -- optimistic locking failure What I've Tried My code that creates new entities is quite complex - it makes entities that have relationships with other entities that could be being created in a separate thread. If I replace my object creation routine with some very simple code just making non-related entries, everything works perfectly. Initially, as well as the exceptions, I was getting a save error saying core data couldn't save due to the merge failing. I read the docs and realised I needed a merge policy on the Managed Object Context I was saving to. I set this up and as this question states, the save error goes away, but the exception remains. My Question Do I need to worry about these exceptions? If I do need to get rid of the exceptions, any ideas on how I do it?

    Read the article

  • Is there a Form.Invoke() method?

    - by rubicon
    Hi, I am new to multithreading (and also to C#) so I hope this is not obvious: In my Form (WinForms application, .NET 2.0) I subscribed to an event that is raised by another object, and on handling this event I wish to change several Controls on my Form. As this event is raised in another thread than the main (UI) thread I want to marshal the call to the Form's thread. I understand I could use the Control.Invoke() method on any Control that I want to change, but as there are several of them I do not wish to do that. When searching the internet I found hints that the Form class itself provides an Invoke() method. See for example: http://marioschneider.blogspot.com/2008/04/invoke-methode-fr-multithread.html (Sorry, as I am I new user I can't seem to post more than one link. I will add more links as comments if possible.) With that, I could just wrap my event handler and then use it as if it was called on the UI thread. However, this doesn't seem to be defined in my environment, and in MSDN's System.Windows.Forms.Form documentation there's also no sign of it. Does this method exist in the .NET-Framework? I find it hard to believe that Form would not supply such a method, as it uses the same message queue the Controls on it do. (Or am I missing something here?)

    Read the article

  • Is this function thread-safe?

    - by kiddo
    Hello all,I am learning multi-threading and for the sake of understanding I have wriiten a small function using multithreading...it works fine.But I just want to know if that thread is safe to use,did I followed the correct rule. void CThreadingEx4Dlg::OnBnClickedOk() { //in thread1 100 elements are copied to myShiftArray(which is a CStringArray) thread1 = AfxBeginThread((AFX_THREADPROC)MyThreadFunction1,this); WaitForSingleObject(thread1->m_hThread,INFINITE); //thread2 waits for thread1 to finish because thread2 is going to make use of myShiftArray(in which thread1 processes it first) thread2 = AfxBeginThread((AFX_THREADPROC)MyThreadFunction2,this); thread3 = AfxBeginThread((AFX_THREADPROC)MyThreadFunction3,this); } UINT MyThreadFunction1(LPARAM lparam) { CThreadingEx4Dlg* pthis = (CThreadingEx4Dlg*)lparam; pthis->MyFunction(0,100); return 0; } UINT MyThreadFunction2(LPARAM lparam) { CThreadingEx4Dlg* pthis = (CThreadingEx4Dlg*)lparam; pthis->MyCommonFunction(0,20); return 0; } UINT MyThreadFunction3(LPARAM lparam) { CThreadingEx4Dlg* pthis = (CThreadingEx4Dlg*)lparam; WaitForSingleObject(pthis->thread3->m_hThread,INFINITE); //here thread3 waits for thread 2 to finish so that thread can continue pthis->MyCommonFunction(21,40); return 0; } void CThreadingEx4Dlg::MyFunction(int minCount,int maxCount) { for(int i=minCount;i<maxCount;i++) { //assume myArray is a CStringArray and it has 100 elemnts added to it. //myShiftArray is a CStringArray -public to the class CString temp; temp = myArray.GetAt(i); myShiftArray.Add(temp); } } void CThreadingEx4Dlg::MyCommonFunction(int min,int max) { for(int i = min;i < max;i++) { CSingleLock myLock(&myCS,TRUE); CString temp; temp = myShiftArray.GetAt(i); //threadArray is CStringArray-public to the class threadArray.Add(temp); } myEvent.PulseEvent(); }

    Read the article

  • Asynchronous callback for network in Objective-C Iphone

    - by vodkhang
    I am working with network request - response in Objective-C. There is something with asynchronous model that I don't understand. In summary, I have a view that will show my statuses from 2 social networks: Twitter and Facebook. When I clicked refresh, it will call a model manager. That model manager will call 2 service helpers to request for latest items. When 2 service helpers receive data, it will pass back to model manager and this model will add all data into a sorted array. What I don't understand here is that : when response from social networks come back, how many threads will handle the response. From my understanding about multithreading and networking (in Java), there must have 2 threads handle 2 responses and those 2 threads will execute the code to add the responses to the array. So, it can have race condition and the program can go wrong right? Is it the correct working model of iphone objective-C? Or they do it in a different way that it will never have race condition and we don't have to care about locking, synchronize? Here is my example code: ModelManager.m - (void)updateMyItems:(NSArray *)items { self.helpers = [self authenticatedHelpersForAction:NCHelperActionGetMyItems]; for (id<NCHelper> helper in self.helpers) { [helper updateMyItems:items]; // NETWORK request here } } - (void)helper:(id <NCHelper>)helper didReturnItems:(NSArray *)items { [self helperDidFinishGettingMyItems:items callback:@selector(model:didGetMyItems:)]; break; } } // some private attributes int *_currentSocialNetworkItemsCount = 0; // to count the number of items of a social network - (void)helperDidFinishGettingMyItems:(NSArray *)items { for (Item *item in items) { _currentSocialNetworkItemsCount ++; } NSLog(@"count: %d", _currentSocialNetworkItemsCount); _currentSocialNetworkItemsCount = 0; } I want to ask if there is a case that the method helperDidFinishGettingMyItems is called concurrently. That means, for example, faceboook returns 10 items, twitter returns 10 items, will the output of count will ever be larger than 10? And if there is only one single thread, how can the thread finishes parsing 1 response and jump to the other response because, IMO, thread is only executed sequently, block of code by block of code

    Read the article

  • how to predict which section have to put in critical section in threading

    - by Lalit Dhake
    Hi , I am using the console application i used multi threading in the same. I just want to know which section have to put inside critical section my code is : .------------------------------------------------------------------------------. public class SendBusReachSMS { public void SchedularEntryPoint() { try { List<ActiveBusAndItsPathInfo> ActiveBusAndItsPathInfoList = BusinessLayer.GetActiveBusAndItsPathInfoList(); if (ActiveBusAndItsPathInfoList != null) { //SMSThreadEntryPoint smsentrypoint = new SMSThreadEntryPoint(); while (true) { foreach (ActiveBusAndItsPathInfo ActiveBusAndItsPathInfoObj in ActiveBusAndItsPathInfoList) { if (ActiveBusAndItsPathInfoObj.isSMSThreadActive == false) { DateTime CurrentTime = System.DateTime.Now; DateTime Bustime = Convert.ToDateTime(ActiveBusAndItsPathInfoObj.busObj.Timing); TimeSpan tsa = Bustime - CurrentTime; if (tsa.TotalMinutes > 0 && tsa.TotalMinutes < 5) { ThreadStart starter = delegate { SMSThreadEntryPointFunction(ActiveBusAndItsPathInfoObj); }; Thread t = new Thread(starter); t.Start(); t.Join(); } } } } } } catch (Exception ex) { Console.WriteLine("==========================================="); Console.WriteLine(ex.Message); Console.WriteLine(ex.InnerException); Console.WriteLine("==========================================="); } } public void SMSThreadEntryPointFunction(ActiveBusAndItsPathInfo objActiveBusAndItsPathInfo) { try { //mutThrd.WaitOne(); String consoleString = "Thread for " + objActiveBusAndItsPathInfo.busObj.Number + "\t" + " on path " + "\t" + objActiveBusAndItsPathInfo.pathObj.PathId; Console.WriteLine(consoleString); TrackingInfo trackingObj = new TrackingInfo(); string strTempBusTime = objActiveBusAndItsPathInfo.busObj.Timing; while (true) { trackingObj = BusinessLayer.get_TrackingInfoForSendingSMS(objActiveBusAndItsPathInfo.busObj.Number); if (trackingObj.latitude != 0.0 && trackingObj.longitude != 0.0) { //calculate distance double distanceOfCurrentToDestination = 4.45; TimeSpan CurrentTime = System.DateTime.Now.TimeOfDay; TimeSpan timeLimit = objActiveBusAndItsPathInfo.sessionInTime - CurrentTime; if ((distanceOfCurrentToDestination <= 5) && (timeLimit.TotalMinutes <= 5)) { Console.WriteLine("Message sent to bus number's parents: " + objActiveBusAndItsPathInfo.busObj.Number); break; } } } // mutThrd.ReleaseMutex(); } catch (Exception ex) { //throw; Console.WriteLine("==========================================="); Console.WriteLine(ex.Message); Console.WriteLine(ex.InnerException); Console.WriteLine("==========================================="); } } } Please help me in multithreading. new topic for me in .net

    Read the article

  • Is this a valid pattern for raising events in C#?

    - by Will Vousden
    Update: For the benefit of anyone reading this, since .NET 4, the lock is unnecessary due to changes in synchronization of auto-generated events, so I just use this now: public static void Raise<T>(this EventHandler<T> handler, object sender, T e) where T : EventArgs { if (handler != null) { handlerCopy(sender, e); } } And to raise it: SomeEvent.Raise(this, new FooEventArgs()); Having been reading one of Jon Skeet's articles on multithreading, I've tried to encapsulate the approach he advocates to raising an event in an extension method like so (with a similar generic version): public static void Raise(this EventHandler handler, object @lock, object sender, EventArgs e) { EventHandler handlerCopy; lock (@lock) { handlerCopy = handler; } if (handlerCopy != null) { handlerCopy(sender, e); } } This can then be called like so: protected virtual void OnSomeEvent(EventArgs e) { this.someEvent.Raise(this.eventLock, this, e); } Are there any problems with doing this? Also, I'm a little confused about the necessity of the lock in the first place. As I understand it, the delegate is copied in the example in the article to avoid the possibility of it changing (and becoming null) between the null check and the delegate call. However, I was under the impression that access/assignment of this kind is atomic, so why is the lock necessary? Update: With regards to Mark Simpson's comment below, I threw together a test: static class Program { private static Action foo; private static Action bar; private static Action test; static void Main(string[] args) { foo = () => Console.WriteLine("Foo"); bar = () => Console.WriteLine("Bar"); test += foo; test += bar; test.Test(); Console.ReadKey(true); } public static void Test(this Action action) { action(); test -= foo; Console.WriteLine(); action(); } } This outputs: Foo Bar Foo Bar This illustrates that the delegate parameter to the method (action) does not mirror the argument that was passed into it (test), which is kind of expected, I guess. My question is will this affect the validity of the lock in the context of my Raise extension method? Update: Here is the code I'm now using. It's not quite as elegant as I'd have liked, but it seems to work: public static void Raise<T>(this object sender, ref EventHandler<T> handler, object eventLock, T e) where T : EventArgs { EventHandler<T> copy; lock (eventLock) { copy = handler; } if (copy != null) { copy(sender, e); } }

    Read the article

  • Problem in suspending 2 threads at the same time in MFC!

    - by kiddo
    I am learning about threading and multithreading..so i just created a small application in which i will update the progressbar and a static text using threading.I vl get two inputs from the user, start and end values for how long the loop should rotate.I have 2threads in my application. Thread1- to update the progressbar(according to the loop) the static text which will show the count(loop count). Thread2 - to update the another static text which will just diplay a name Basically if the user clicks start, the progressbar steps up and at the same time filecount and the name are displayed parallely. There's is another operation where if the user clicks pause it(thread) has to suspend until the user clicks resume. The problem is,the above will not work(will not suspend and resume) for both thread..but works for a singlw thread. Please check the code to get an idea and reply me what can done! on button click start void CThreadingEx3Dlg::OnBnClickedStart() { m_ProgressBar.SetRange(start,end); myThread1 = AfxBeginThread((AFX_THREADPROC)MyThreadFunction1,this); myThread2 = AfxBeginThread((AFX_THREADPROC)MyThreadFunction2,this); } thread1 UINT MyThreadFunction1(LPARAM lparam) { CThreadingEx3Dlg* pthis = (CThreadingEx3Dlg*)lparam; for(int intvalue =pthis->start;intvalue<=pthis->end; ++intvalue) { pthis->SendMessage(WM_MY_THREAD_MESSAGE1,intvalue); } return 0; } thread1 function LRESULT CThreadingEx3Dlg::OnThreadMessage1(WPARAM wparam,LPARAM lparam) { int nProgress= (int)wparam; m_ProgressBar.SetPos(nProgress); CString strStatus; strStatus.Format(L"Thread1:Processing item: %d", nProgress); m_Static.SetWindowText(strStatus); Sleep(100); return 0; } thread2 UINT MyThreadFunction2(LPARAM lparam) { CThreadingEx3Dlg* pthis = (CThreadingEx3Dlg*)lparam; for(int i =pthis->start;i<=pthis->end;i++) { pthis->SendMessage(WM_MY_THREAD_MESSAGE2,i); } return 0; } thread2 function LRESULT CThreadingEx3Dlg::OnThreadMessage2(WPARAM wparam,LPARAM lparam) { m_Static1.GetDlgItem(IDC_STATIC6); m_Static1.SetWindowTextW(L"Thread2 Running"); Sleep(100); m_Static1.SetWindowTextW(L""); Sleep(100); return TRUE; } void CThreadingEx3Dlg::OnBnClickedPause() { // TODO: Add your control notification handler code here if(!m_Track) { m_Track = TRUE; GetDlgItem(IDCANCEL)->SetWindowTextW(L"Resume"); myThread1->SuspendThread(); WaitForSingleObject(myThread1->m_hThread,INFINITE); myThread2->SuspendThread(); m_Static.SetWindowTextW(L"Paused.."); } else { m_Track = FALSE; GetDlgItem(IDCANCEL)->SetWindowTextW(L"Pause"); myThread1->ResumeThread(); myThread2->ResumeThread(); /*myEventHandler.SetEvent(); WaitForSingleObject(myThread1->m_hThread,INFINITE);*/ } }

    Read the article

< Previous Page | 9 10 11 12 13 14 15 16 17 18 19 20  | Next Page >