Search Results

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

Page 20/66 | < Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >

  • Strange behaviour of code inside TransactionScope?

    - by Krishna
    We are facing a very complex issue in our production application. We have a WCF method which creates a complex Entity in the database with all its relation. public void InsertEntity(Entity entity) { using(TransactionScope scope = new TransactionScope()) { EntityDao.Create(entity); } } EntityDao.Create(entity) method is very complex and has huge pieces of logic. During the entire process of creation it creates several child entities and also have several queries to database. During the entire WCF request of entity creation usually Connection is maintained in a ThreadStatic variable and reused by the DAOs. Although some of the queries in DAO described in step 2 uses a new connection and closes it after use. Overall we have seen that the above process behaviour is erratic. Some of the queries in the inner DAO does not even return actual data from the database? The same query when run to the actaul data store gives correct result. What can be possible reason of this behaviour?

    Read the article

  • How to make Stack.Pop threadsafe

    - by user260197
    I am using the BlockingQueue code posted in this question, but realized I needed to use a Stack instead of a Queue given how my program runs. I converted it to use a Stack and renamed the class as needed. For performance I removed locking in Push, since my producer code is single threaded. My problem is how can thread working on the (now) thread safe Stack know when it is empty. Even if I add another thread safe wrapper around Count that locks on the underlying collection like Push and Pop do, I still run into the race condition that access Count and then Pop are not atomic. Possible solutions as I see them (which is preferred and am I missing any that would work better?): Consumer threads catch the InvalidOperationException thrown by Pop(). Pop() return a nullptr when _stack-Count == 0, however C++-CLI does not have the default() operator ala C#. Pop() returns a boolean and uses an output parameter to return the popped element. Here is the code I am using right now: generic <typename T> public ref class ThreadSafeStack { public: ThreadSafeStack() { _stack = gcnew Collections::Generic::Stack<T>(); } public: void Push(T element) { _stack->Push(element); } T Pop(void) { System::Threading::Monitor::Enter(_stack); try { return _stack->Pop(); } finally { System::Threading::Monitor::Exit(_stack); } } public: property int Count { int get(void) { System::Threading::Monitor::Enter(_stack); try { return _stack->Count; } finally { System::Threading::Monitor::Exit(_stack); } } } private: Collections::Generic::Stack<T> ^_stack; };

    Read the article

  • Techniques for modeling a dynamic dataflow with Java concurrency API

    - by Maian
    Is there an elegant way to model a dynamic dataflow in Java? By dataflow, I mean there are various types of tasks, and these tasks can be "connected" arbitrarily, such that when a task finishes, successor tasks are executed in parallel using the finished tasks output as input, or when multiple tasks finish, their output is aggregated in a successor task (see flow-based programming). By dynamic, I mean that the type and number of successors tasks when a task finishes depends on the output of that finished task, so for example, task A may spawn task B if it has a certain output, but may spawn task C if has a different output. Another way of putting it is that each task (or set of tasks) is responsible for determining what the next tasks are. Sample dataflow for rendering a webpage: I have as task types: file downloader, HTML/CSS renderer, HTML parser/DOM builder, image renderer, JavaScript parser, JavaScript interpreter. File downloader task for HTML file HTML parser/DOM builder task File downloader task for each embedded file/link If image, image renderer If external JavaScript, JavaScript parser JavaScript interpreter Otherwise, just store in some var/field in HTML parser task JavaScript parser for each embedded script JavaScript interpreter Wait for above tasks to finish, then HTML/CSS renderer (obviously not optimal or perfectly correct, but this is simple) I'm not saying the solution needs to be some comprehensive framework (in fact, the closer to the JDK API, the better), and I absolutely don't want something as heavyweight is say Spring Web Flow or some declarative markup or other DSL. To be more specific, I'm trying to think of a good way to model this in Java with Callables, Executors, ExecutorCompletionServices, and perhaps various synchronizer classes (like Semaphore or CountDownLatch). There are a couple use cases and requirements: Don't make any assumptions on what executor(s) the tasks will run on. In fact, to simplify, just assume there's only one executor. It can be a fixed thread pool executor, so a naive implementation can result in deadlocks (e.g. imagine a task that submits another task and then blocks until that subtask is finished, and now imagine several of these tasks using up all the threads). To simplify, assume that the data is not streamed between tasks (task output-succeeding task input) - the finishing task and succeeding task won't exist together, so the input data to the succeeding task will not be changed by the preceeding task (since it's already done). There are only a couple operations that the dataflow "engine" should be able to handle: A mechanism where a task can queue more tasks A mechanism whereby a successor task is not queued until all the required input tasks are finished A mechanism whereby the main thread (or other threads not managed by the executor) blocks until the flow is finished A mechanism whereby the main thread (or other threads not managed by the executor) blocks until certain tasks have finished Since the dataflow is dynamic (depends on input/state of the task), the activation of these mechanisms should occur within the task code, e.g. the code in a Callable is itself responsible for queueing more Callables. The dataflow "internals" should not be exposed to the tasks (Callables) themselves - only the operations listed above should be available to the task. Note that the type of the data is not necessarily the same for all tasks, e.g. a file download task may accept a File as input but will output a String. If a task throws an uncaught exception (indicating some fatal error requiring all dataflow processing to stop), it must propagate up to the thread that initiated the dataflow as quickly as possible and cancel all tasks (or something fancier like a fatal error handler). Tasks should be launched as soon as possible. This along with the previous requirement should preclude simple Future polling + Thread.sleep(). As a bonus, I would like to dataflow engine itself to perform some action (like logging) every time task is finished or when no has finished in X time since last task has finished. Something like: ExecutorCompletionService<T> ecs; while (hasTasks()) { Future<T> future = ecs.poll(1 minute); some_action_like_logging(); if (future != null) { future.get() ... } ... } Are there straightforward ways to do all this with Java concurrency API? Or if it's going to complex no matter what with what's available in the JDK, is there a lightweight library that satisfies the requirements? I already have a partial solution that fits my particular use case (it cheats in a way, since I'm using two executors, and just so you know, it's not related at all to the web browser example I gave above), but I'd like to see a more general purpose and elegant solution.

    Read the article

  • What is the impact of Thread.Sleep(1) in C#?

    - by Justin Tanner
    In a windows form application what is the impact of calling Thread.Sleep(1) as illustrated in the following code: public Constructor() { Thread thread = new Thread(Task); thread.IsBackground = true; thread.Start(); } private void Task() { while (true) { // do something Thread.Sleep(1); } } Will this thread hog all of the available CPU? What profiling techniques can I use to measure this Thread's CPU usage ( other than task manager )?

    Read the article

  • Boost Thread Synchronization

    - by Dave18
    I don't see synchronized output when i comment the the line wait(1) in thread(). can I make them run at the same time (one after another) without having to use 'wait(1)'? #include <boost/thread.hpp> #include <iostream> void wait(int seconds) { boost::this_thread::sleep(boost::posix_time::seconds(seconds)); } boost::mutex mutex; void thread() { for (int i = 0; i < 100; ++i) { wait(1); mutex.lock(); std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl; mutex.unlock(); } } int main() { boost::thread t1(thread); boost::thread t2(thread); t1.join(); t2.join(); }

    Read the article

  • Winforms application hangs when switching to another app

    - by joseluisrod
    Hi, I believe I have a potential threading issue. I have a user control that contains the following code: private void btnVerify_Click(object sender, EventArgs e) { if (!backgroundWorkerVerify.IsBusy) { backgroundWorkerVerify.RunWorkerAsync(); } } private void backgroundWorkerVerify_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) { VerifyAppointments(); } private void backgroundWorkerVerify_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { MessageBox.Show("Information was Verified.", "Verify", MessageBoxButtons.OK, MessageBoxIcon.Information); CloseEvent(); } vanilla code. but the issue I have is that when the application is running and the users tabs to another application when they return to mine the application is hung, they get a blank screen and they have to kill it. This started when I put the threading code. Could I have some rogue threads out there? what is the best way to zero in a threading problem? The issue can't be recreated on my machine...I know I must be missing something on how to dispose of a backgroundworker properly. Any thoughts are appreciated, Thanks, Jose

    Read the article

  • Starting one BlackBerry screen from another.

    - by DanG
    I've recently run into a snag while putting on the finishing touches for my BlackBerry app. I'm building a login screen which, if the user is successful in logging in, goes to a data loading screen, and then to a home screen. From the home screen, you can use the app. Everything works great but one thing, I can't seamlessly move from the login screen to the loading screen, to the home screen. I can move from the login screen to the loading screen ok, because I'm doing that via a button click which is on the GUI thread, but then I have the login screen at the bottom of the stack and can't get it out using the dismiss method. Once in the loading screen, I can't push the home screen because I'm not doing it via the gui method, though I'm able to update the GUI via the following piece of code: private void checkData(){ Timer loadingTimer = new Timer(); TimerTask loadingTask = new TimerTask() { public void run() { // set the progress bar progressGaugeField.setValue(DataManager.getDataLoaded()); // for repainting the screen invalidate(); } }; loadingTimer.scheduleAtFixedRate(loadingTask, 500, 500); } Does anyone know how to solve my problem of moving seamlessly from the login screen to the loading screen to the home screen? Note: once I'm at the home screen I'd like to have it be the only screen on the stack. Thanks!

    Read the article

  • Cross Thread Exception in PropertyChangedEvent in WPF

    - by Ashish Ashu
    I have a ListView that is binded to my custom collection. At run time , I am updating the certain properties of my entity in my custom collection in my ViewModel. At the same time , I am also doing the custom sorting in the listview. The custom sorting is applicable when I click on the any column header of the listview. For example, I am updating the current datetime on my entity on every 5 seconds and simulaneously , I am applying custom sorting based on DateTime. (The Listview is third party control). Hence I am doing two operations on my custom collection at the same time. Should I pass the dispatcher of my control in the view model and call any methods ( which updates any entity in my custom collection ) through UI dispatcher ?

    Read the article

  • Please help. Creating threads and wait till finsh

    - by Raj Aththanayake
    Hi I have two method calls that I want to call using two threads. Then I want them to wait till method executions get completed before continuing. My sample solution is something like below. public static void Main() { Console.WriteLine("Main thread starting."); String[] strThreads = new String[] { "one", "two" }; String ctemp = string.Empty; foreach (String c in strThreads) { ctemp = c; Thread thread = new Thread(delegate() { MethodCall(ctemp); }); thread.Start(); thread.Join(); } Console.WriteLine("Main thread ending."); Console.Read(); } public static void MethodCalls(string number) { Console.WriteLine("Method call " + number); } Is this will do the job? Or is there another better way to do the same thing?

    Read the article

  • Synchronization of Nested Data Structures between Threads in Java

    - by Dominik
    I have a cache implementation like this: class X { private final Map<String, ConcurrentMap<String, String>> structure = new HashMap...(); public String getValue(String context, String id) { // just assume for this example that there will be always an innner map final ConcurrentMap<String, String> innerStructure = structure.get(context); String value = innerStructure.get(id); if(value == null) { synchronized(structure) { // can I be sure, that this inner map will represent the last updated // state from any thread? value = innerStructure.get(id); if(value == null) { value = getValueFromSomeSlowSource(id); innerStructure.put(id, value); } } } return value; } } Is this implementation thread-safe? Can I be sure to get the last updated state from any thread inside the synchronized block? Would this behaviour change if I use a java.util.concurrent.ReentrantLock instead of a synchronized block, like this: ... if(lock.tryLock(3, SECONDS)) { try { value = innerStructure.get(id); if(value == null) { value = getValueFromSomeSlowSource(id); innerStructure.put(id, value); } } finally { lock.unlock(); } } ... I know that final instance members are synchronized between threads, but is this also true for the objects held by these members? Maybe this is a dumb question, but I don't know how to test it to be sure, that it works on every OS and every architecture.

    Read the article

  • Synchronizing issue: I want the main thread to be run before another thread but it sometimes doesn´t

    - by Rox
    I have done my own small concurrency framework (just for learning purposes) inspired by the java.util.concurrency package. This is about the Callable/Future mechanism. My code below is the whole one and is compilable and very easy to understand. My problem is that sometimes I run into a deadlock where the first thread (the main thread) awaits for a signal from the other thread. But then the other thread has already notified the main thread before the main thread went into waiting state, so the main thread cannot wake up. FutureTask.get() should always be run before FutureTask.run() but sometimes the run() method (which is called by new thread) runs before the get() method (which is called by main thread). I don´t know how I can prevent that. This is a pseudo code of how I want the two threads to be run. //From main thread: Executor.submit().get() (in get() the main thread waits for new thread to notify) ->submit() calls Executor.execute(FutureTask object) -> execute() starts new thread -> new thread shall notify `main thread` I cannot understand how the new thread can start up and run faster than the main thread that actually starts the new thread. Main.java: public class Main { public static void main(String[] args) { new ExecutorServiceExample(); } public Main() { ThreadExecutor executor = new ThreadExecutor(); Integer i = executor.submit(new Callable<Integer>() { @Override public Integer call() { return 10; } }).get(); System.err.println("Value: "+i); } } ThreadExecutor.java: public class ThreadExecutor { public ThreadExecutor() {} protected <V> RunnableFuture<V> newTaskFor(Callable c) { return new FutureTask<V>(c); } public <V> Future<V> submit(Callable<V> task) { if (task == null) throw new NullPointerException(); RunnableFuture<V> ftask = newTaskFor(task); execute(ftask); return ftask; } public void execute(Runnable r) { new Thread(r).start(); } } FutureTask.java: import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; public class FutureTask<V> implements RunnableFuture<V> { private Callable<V> callable; private volatile V result; private ReentrantLock lock = new ReentrantLock(); private Condition condition = lock.newCondition(); public FutureTask(Callable callable) { if (callable == null) throw new NullPointerException(); this.callable = callable; } @Override public void run() { acquireLock(); System.err.println("RUN"+Thread.currentThread().getName()); V v = this.callable.call(); set(v); condition.signal(); releaseLock(); } @Override public V get() { acquireLock(); System.err.println("GET "+Thread.currentThread().getName()); try { condition.await(); } catch (InterruptedException ex) { Logger.getLogger(FutureTask.class.getName()).log(Level.SEVERE, null, ex); } releaseLock(); return this.result; } public void set(V v) { this.result = v; } private void acquireLock() { lock.lock(); } private void releaseLock() { lock.unlock(); } } And the interfaces: public interface RunnableFuture<V> extends Runnable, Future<V> { @Override void run(); } public interface Future<V> { V get(); } public interface Callable<V> { V call(); }

    Read the article

  • Is DataRow thread safe? How to update a single datarow in a datatable using multiple threads? - .net

    - by NLV
    Hello all I want to update a single datarow in a datatable using multiple threads. Is this actually possible? I've written the following code implementing a simple multi-threading to update a single datarow. I get different results each time. Why is it so? public partial class Form1 : Form { private static DataTable dtMain; private static string threadMsg = string.Empty; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Thread[] thArr = new Thread[5]; dtMain = new DataTable(); dtMain.Columns.Add("SNo"); DataRow dRow; dRow = dtMain.NewRow(); dRow["SNo"] = 5; dtMain.Rows.Add(dRow); dtMain.AcceptChanges(); ThreadStart ts = new ThreadStart(delegate { dtUpdate(); }); thArr[0] = new Thread(ts); thArr[1] = new Thread(ts); thArr[2] = new Thread(ts); thArr[3] = new Thread(ts); thArr[4] = new Thread(ts); thArr[0].Start(); thArr[1].Start(); thArr[2].Start(); thArr[3].Start(); thArr[4].Start(); while (!WaitTillAllThreadsStopped(thArr)) { Thread.Sleep(500); } foreach (Thread thread in thArr) { if (thread != null && thread.IsAlive) { thread.Abort(); } } dgvMain.DataSource = dtMain; } private void dtUpdate() { for (int i = 0; i < 1000; i++) { try { dtMain.Rows[0][0] = Convert.ToInt32(dtMain.Rows[0][0]) + 1; dtMain.AcceptChanges(); } catch { continue; } } } private bool WaitTillAllThreadsStopped(Thread[] threads) { foreach (Thread thread in threads) { if (thread != null && thread.ThreadState == ThreadState.Running) { return false; } } return true; } } Any thoughts on this? Thank you NLV

    Read the article

  • Problem with stackless python, cannot write to a dict

    - by ANON
    I have simple map-reduce type algorithm, which I want to implement in python and make use of multiple cores. I read somewhere that threads using native thread module in 2.6 dont make use of multiple cores. is that true? I even implemented it using stackless python however i am getting into weird errors [Update: a quick search showed that the stack less does not allows multiple cores So are their any other alternatives?] def Propagate(start,end): print "running Thread with range: ",start,end def maxVote(nLabels): count = {} maxList = [] maxCount = 0 for nLabel in nLabels: if nLabel in count: count[nLabel] += 1 else: count[nLabel] = 1 #Check if the count is max if count[nLabel] > maxCount: maxCount = count[nLabel]; maxList = [nLabel,] elif count[nLabel]==maxCount: maxList.append(nLabel) return random.choice(maxList) for num in range(start,end): node=MapList[num] nLabels = [Label[k] for k in Adj[node]] if (nLabels!=[]): Label[node] = maxVote(nLabels) else: Label[node]=node However in above code the values assigned to Label, that is the change in dictionary are lost. Above propagate function is used as callable for MicroThreads (i.e. TaskLets)

    Read the article

  • Do Scala and Erlang use green threads?

    - by CHAPa
    I've been reading a lot about how Scala and Erlang does lightweight threads and their concurrency model (actors). However, I have my doubts. Do Scala and Erlang use an approach similar to the old thread model used by Java (green threads) ? For example, suppose that there is a machine with 2 cores, so the Scala/Erlang environment will fork one thread per processor? The other threads will be scheduled by user-space (Scala VM / Erlang VM ) environment. Is this correct? Under the hood, how does this really work?

    Read the article

  • Socket server with multiple clients, sending messages to many clients without hurting liveliness

    - by Karl Johanson
    I have a small socket server, and I need to distribute various messages from client-to-client depending on different conditionals. However I think I have a small problem with livelyness in my current code, and is there anything wrong in my approach: public class CuClient extends Thread { Socket socket = null; ObjectOutputStream out; ObjectInputStream in; CuGroup group; public CuClient(Socket s, CuGroup g) { this.socket = s; this.group = g; out = new ObjectOutputStream(this.socket.getOutputStream()); out.flush(); in = new ObjectInputStream(this.socket.getInputStream()); } @Override public void run() { String cmd = ""; try { while (!cmd.equals("client shutdown")) { cmd = (String) in.readObject(); this.group.broadcastToGroup(this, cmd); } out.close(); in.close(); socket.close(); } catch (Exception e) { System.out.println(this.getName()); e.printStackTrace(); } } public void sendToClient(String msg) { try { this.out.writeObject(msg); this.out.flush(); } catch (IOException ex) { } } And my CuGroup: public class CuGroup { private Vector<CuClient> clients = new Vector<CuClient>(); public void addClient(CuClient c) { this.clients.add(c); } void broadcastToGroup(CuClient clientName, String cmd) { Iterator it = this.clients.iterator(); while (it.hasNext()) { CuClient cu = (CuClient)it.next(); cu.sendToClient(cmd); } } } And my main-class: public class SmallServer { public static final Vector<CuClient> clients = new Vector<CuClient>(10); public static boolean serverRunning = true; private ServerSocket serverSocket; private CuGroup group = new CuGroup(); public void body() { try { this.serverSocket = new ServerSocket(1337, 20); System.out.println("Waiting for clients\n"); do { Socket s = this.serverSocket.accept(); CuClient t = new CuClient(s,group); System.out.println("SERVER: " + s.getInetAddress() + " is connected!\n"); t.start(); } while (this.serverRunning); } catch (IOException ex) { ex.printStackTrace(); } } public static void main(String[] args) { System.out.println("Server"); SmallServer server = new SmallServer(); server.body(); } } Consider the example with many more groups, maybe a Collection of groups. If they all synchronize on a single Object, I don't think my server will be very fast. I there a pattern or something that can help my liveliness?

    Read the article

  • Thread Synchronisation 101

    - by taspeotis
    Previously I've written some very simple multithreaded code, and I've always been aware that at any time there could be a context switch right in the middle of what I'm doing, so I've always guarded access the shared variables through a CCriticalSection class that enters the critical section on construction and leaves it on destruction. I know this is fairly aggressive and I enter and leave critical sections quite frequently and sometimes egregiously (e.g. at the start of a function when I could put the CCriticalSection inside a tighter code block) but my code doesn't crash and it runs fast enough. At work my multithreaded code needs to be a tighter, only locking/synchronising at the lowest level needed. At work I was trying to debug some multithreaded code, and I came across this: EnterCriticalSection(&m_Crit4); m_bSomeVariable = true; LeaveCriticalSection(&m_Crit4); Now, m_bSomeVariable is a Win32 BOOL (not volatile), which as far as I know is defined to be an int, and on x86 reading and writing these values is a single instruction, and since context switches occur on an instruction boundary then there's no need for synchronising this operation with a critical section. I did some more research online to see whether this operation did not need synchronisation, and I came up with two scenarios it did: The CPU implements out of order execution or the second thread is running on a different core and the updated value is not written into RAM for the other core to see; and The int is not 4-byte aligned. I believe number 1 can be solved using the "volatile" keyword. In VS2005 and later the C++ compiler surrounds access to this variable using memory barriers, ensuring that the variable is always completely written/read to the main system memory before using it. Number 2 I cannot verify, I don't know why the byte alignment would make a difference. I don't know the x86 instruction set, but does mov need to be given a 4-byte aligned address? If not do you need to use a combination of instructions? That would introduce the problem. So... QUESTION 1: Does using the "volatile" keyword (implicity using memory barriers and hinting to the compiler not to optimise this code) absolve a programmer from the need to synchronise a 4-byte/8-byte on x86/x64 variable between read/write operations? QUESTION 2: Is there the explicit requirement that the variable be 4-byte/8-byte aligned? I did some more digging into our code and the variables defined in the class: class CExample { private: CRITICAL_SECTION m_Crit1; // Protects variable a CRITICAL_SECTION m_Crit2; // Protects variable b CRITICAL_SECTION m_Crit3; // Protects variable c CRITICAL_SECTION m_Crit4; // Protects variable d // ... }; Now, to me this seems excessive. I thought critical sections synchronised threads between a process, so if you've got one you can enter it and no other thread in that process can execute. There is no need for a critical section for each variable you want to protect, if you're in a critical section then nothing else can interrupt you. I think the only thing that can change the variables from outside a critical section is if the process shares a memory page with another process (can you do that?) and the other process starts to change the values. Mutexes would also help here, named mutexes are shared across processes, or only processes of the same name? QUESTION 3: Is my analysis of critical sections correct, and should this code be rewritten to use mutexes? I have had a look at other synchronisation objects (semaphores and spinlocks), are they better suited here? QUESTION 4: Where are critical sections/mutexes/semaphores/spinlocks best suited? That is, which synchronisation problem should they be applied to. Is there a vast performance penalty for choosing one over the other? And while we're on it, I read that spinlocks should not be used in a single-core multithreaded environment, only a multi-core multithreaded environment. So, QUESTION 5: Is this wrong, or if not, why is it right? Thanks in advance for any responses :)

    Read the article

  • Cooperative/Non-preemptive threading avoiding threadlooks?

    - by Wayne
    Any creative ideas to avoid deadlocks on a yield or sleep with cooperative/non-preemptive multitasking without doing an O/S Thread.Sleep(10)? Typically the yield or sleep call will call back into the scheduler to run other tasks. But this can sometime produce deadlocks. Some background: This application has enormous need for speed and, so far, it's extremely fast as compared to other systems in the same industry. One of the speed techniques is cooperative/non-preemptive threading rather then the cost of a context switch from O/S threads. The high level design a priority manager which calls out to tasks depending on priority and processing time. Each task does one "iteration" of work and returns to wait its turn again in the priority queue. The tricky thing with non-preemptive threading is what to do when you want to a particular task to stop in the middle of work and wait for some other event from a different task before continuing. In this case, we have 3 tasks, A B and C where A is a controller that must synchronize the activity of B and C. First, A starts both B and C. Then B yields so C gets invoked. When C yields, A sees they are both inactive, decides it's time for B to run but not time for C yet. Well B is now stuck in a yield that has called C, so it can never run. Sincerely, Wayne

    Read the article

  • how to find the active thread count?

    - by DayOne
    Hi, i have a c# program which calls into a c++ library. The c# programs process has a high thread count 50 - 60. Most seem to be created in c++ and i supect most are suspended/waiting. How do i find how many of these threads are active at a given point in time? thanks

    Read the article

  • Linux 2.6.31 Scheduler and Multithreaded Jobs

    - by dsimcha
    I run massively parallel scientific computing jobs on a shared Linux computer with 24 cores. Most of the time my jobs are capable of scaling to 24 cores when nothing else is running on this computer. However, it seems like when even one single-threaded job that isn't mine is running, my 24-thread jobs (which I set for high nice values) only manage to get ~1800% CPU (using Linux notation). Meanwhile, about 500% of the CPU cycles (again, using Linux notation) are idle. Can anyone explain this behavior and what I can do about it to get all of the 23 cores that aren't being used by someone else? Notes: In case it's relevant, I have observed this on slightly different kernel versions, though I can't remember which off the top of my head. The CPU architecture is x64. Is it at all possible that the fact that my 24-core jobs are 32-bit and the other jobs I'm competing w/ are 64-bit is relevant? Edit: One thing I just noticed is that going up to 30 threads seems to alleviate the problem to some degree. It gets me up to ~2100% CPU.

    Read the article

  • Tinyxml Multi Task

    - by shaimagz
    I have a single xml file and every new thread of the program (BHO) is using the same Tinyxml file. every time a new window is open in the program, it runs this code: const char * xmlFileName = "C:\\browsarityXml.xml"; TiXmlDocument doc(xmlFileName); doc.LoadFile(); //some new lines in the xml.. and than save: doc.SaveFile(xmlFileName); The problem is that after the first window is adding new data to the xml and saves it, the next window can't add to it. although the next one can read the data in the xml, it can't write to it. I thought about two possibilities to make it work, but I don't know how to implement them: Destroy the doc object when I'm done with it. Some function in Tinyxml library to unload the file. Any help or better understanding of the problem will be great. Thanks.

    Read the article

  • Help needed with InvokeRequired for Web.UI

    - by Ali
    I have a multi-threaded application in C# which tries to write to a TextBox in a Windows.Forms created by another thread. As threads cannot modify what has not been created by them, I was using InvokeRequired as shown on the code below, to solve this problem. public delegate void MessageDelegate(Communication message); void agent_MessageReceived(Communication message) { if (InvokeRequired) { BeginInvoke(new MessageDelegate(agent_MessageReceived), new object[] { message }); } else { TextBox1.Text += message.Body; } } Now I need to do the same for a TextBox in an ASP.NET app, but apparently neither InvokeRequired nor BeginInvoke exist for TextBox in a Web.UI. What can I do?

    Read the article

  • How to mmap the stack for the clone() system call on linux?

    - by Joseph Garvin
    The clone() system call on Linux takes a parameter pointing to the stack for the new created thread to use. The obvious way to do this is to simply malloc some space and pass that, but then you have to be sure you've malloc'd as much stack space as that thread will ever use (hard to predict). I remembered that when using pthreads I didn't have to do this, so I was curious what it did instead. I came across this site which explains, "The best solution, used by the Linux pthreads implementation, is to use mmap to allocate memory, with flags specifying a region of memory which is allocated as it is used. This way, memory is allocated for the stack as it is needed, and a segmentation violation will occur if the system is unable to allocate additional memory." The only context I've ever heard mmap used in is for mapping files into memory, and indeed reading the mmap man page it takes a file descriptor. How can this be used for allocating a stack of dynamic length to give to clone()? Is that site just crazy? ;) In either case, doesn't the kernel need to know how to find a free bunch of memory for a new stack anyway, since that's something it has to do all the time as the user launches new processes? Why does a stack pointer even need to be specified in the first place if the kernel can already figure this out?

    Read the article

  • JScrollPane Scrolls Down with Long Text in JEditorPane

    - by Jim
    Hello, I want to have a JEditorPane inside a JScrollPane. When the user clicks a button, the click listener will create a textEditor, call jscrollpane.setViewPort(textEditor), call textEditor.setText(String) to fill it with editable text, and call jscrollpane.getVerticalScrollBar().setValue(0). In case you're wondering, yes, the setText() must come after the setViewPort() for reasons that aren't on topic. Here is the problem: After the user clicks the button, the JScrollPane's view scrolls all the way to the bottom. I want the scrollbar to be at the top, as per the last line in my click listener. I popped open a debugger, and to my horror, discovered that the jscrollpane's viewport is being forced down to the bottom after the conclusion of the click listener (when pumping filters). It appears that Swing is delaying the population of the editor/jscrollpane until after the conclusion of the clicklistener, but is calling the scrollbar command first. Thus, the undesired behavior. Anyway, I'm wondering if there is a clean solution. It seems that wanting a scrollpane to be scrolled to the top after modification would be a reasonably common requirement, so I'm assuming this is a well-solved problem. Thanks!

    Read the article

  • Running another process without GUI freezing

    - by Adam
    I'm having trouble getting my GUI to appear and not freeze while running (and waiting for) an outside process. In this case, drivers.exe is a very simply program where the user simply clicks "OK". So whenever I click OK, it exits. I am trying to simply make my status strip count numbers up (really fast) as drivers.exe is executing. But in practice, my GUI never appears at all until drivers.exe exits. private void run_drivers() { Console.WriteLine("Start Driver"); int driver_timeout_in_minutes = 20; System.Diagnostics.Process driverproc = System.Diagnostics.Process.Start(Application.StartupPath + "\\" + "drivers.exe"); driverproc.WaitForExit(driver_timeout_in_minutes * 1000 * 60); //uses milliseconds, we must convert } private void Form1_Load(object sender, EventArgs e) { ThreadStart worker = new ThreadStart(run_drivers); Console.WriteLine("Main - Creating worker thread"); toolStripStatusLabel1.Text = "hi"; Thread t = new Thread(worker); t.IsBackground = true; t.Start(); Console.WriteLine("Main - Have requested the start of worker thread"); int i = 0; while (t.IsAlive) { i++; toolStripStatusLabel1.Text = i.ToString(); } Console.WriteLine("Dead"); }

    Read the article

< Previous Page | 16 17 18 19 20 21 22 23 24 25 26 27  | Next Page >