Search Results

Search found 9705 results on 389 pages for 'boost thread'.

Page 10/389 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • How do I get the size of the boost buffer

    - by Anonymous
    I am trying to make an asynchronised server in visual studio and I use boost::asio::async_read(m_socket, boost::asio::buffer(m_buffer), boost::bind(&tcp_connection::handle_read, shared_from_this(), boost::asio::placeholders::error)); to get the buffer to be put in m_buffer boost::array<char, 256> m_buffer; but how do I get the size of this thing, m_buffer? size() didn't work, end() didn't work.. Any help would be fantastic. Thanks in advance.

    Read the article

  • Boost ASIO read X bytes synchroniously into a vector

    - by xeross
    Hey, I've been attempting to write a client/server app with boost now, so far it sends and receives but I can't seem to just read X bytes into a vector. If I use the following code vector<uint8_t> buf; for (;;) { buf.resize(4); boost::system::error_code error; size_t len = socket.read_some(boost::asio::buffer(buf), error); if (error == boost::asio::error::eof) break; // Connection closed cleanly by peer. else if (error) throw boost::system::system_error(error); // Some other error. } And the packet is bigger then 4 bytes then it seems it keeps writing into those 4 bytes until the entire packet has been received, however I want it to fetch 4 bytes, then allow me to parse them, and then get the rest of the packet. Can anyone provide me with a working example, or at least a pointer on how to make it work properly ? Regards, Xeross

    Read the article

  • how to use replace_regex_copy() from boost::algorithm library?

    - by Vincenzo
    This is my code: #include <string> #include <boost/algorithm/string/regex.hpp> string f(const string& s) { using namespace boost::algorithm; return replace_regex_copy(s, "\\w", "?"); } This is what compiler says: no matching function for call to ‘replace_regex_copy(const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&, std::string, std::string) The link to the library: http://www.boost.org/doc/libs/1_43_0/doc/html/boost/algorithm/replace_regex_copy.html Could anyone please help? Thanks! ps. Boost library is in place, since other functions from it work fine.

    Read the article

  • Using * Width & Precision Specifiers With boost::format

    - by John Dibling
    I am trying to use width and precision specifiers with boost::format, like this: #include <boost\format.hpp> #include <string> int main() { int n = 5; std::string s = (boost::format("%*.*s") % (n*2) % (n*2) % "Hello").str(); return 0; } But this doesn't work because boost::format doesn't support the * specifier. Boost throws an exception when parsing the string. Is there a way to accomplish the same goal, preferably using a drop-in replacement?

    Read the article

  • What are the differences between currently executing .NET thread and Win32 thread

    - by Ybbest
    I am reading the Asp.net security documentation on msdn.I come across these tow terms and get really confused. # WindowsIdentity = WindowsIdentity.GetCurrent() which returns the identity of the security context of the currently executing Win32 thread. # Thread = Thread.CurrentPrincipal which returns the principal of the currently executing .NET thread which rides on top of the Win32 thread.

    Read the article

  • what are the differences between currectly excecuting .net thread and Win32 thread

    - by Ybbest
    I am reading the Asp.net security documentation on msdn.I come across these tow terms and get really confused. # WindowsIdentity = WindowsIdentity.GetCurrent(), which returns the identity of the security context of the currently executing Win32 thread. # Thread = Thread.CurrentPrincipal which returns the principal of the currently executing .NET thread which rides on top of the Win32 thread.

    Read the article

  • what are the differences between correctly executing .net thread and Win32 thread

    - by Ybbest
    I am reading the Asp.net security documentation on msdn.I come across these tow terms and get really confused. # WindowsIdentity = WindowsIdentity.GetCurrent(), which returns the identity of the security context of the currently executing Win32 thread. # Thread = Thread.CurrentPrincipal which returns the principal of the currently executing .NET thread which rides on top of the Win32 thread.

    Read the article

  • boost::filesystem - how to create a boost path from a windows path string on posix plattforms?

    - by VolkA
    I'm reading path names from a database which are stored as relative paths in Windows format, and try to create a boost::filesystem::path from them on a Unix system. What happens is that the constructor call interprets the whole string as the filename. I need the path to be converted to a correct Posix path as it will be used locally. I didn't find any conversion functions in the boost::filesystem reference, nor through google. Am I just blind, is there an obvious solution? If not, how would you do this? Example: std::string win_path("foo\\bar\\asdf.xml"); std::string posix_path("foo/bar/asdf.xml"); // loops just once, as part is the whole win_path interpreted as a filename boost::filesystem::path boost_path(win_path); BOOST_FOREACH(boost::filesystem::path part, boost_path) { std::cout << part << std::endl; } // prints each path component separately boost::filesystem::path boost_path_posix(posix_path); BOOST_FOREACH(boost::filesystem::path part, boost_path_posix) { std::cout << part << std::endl; }

    Read the article

  • Thread placement policies on NUMA systems - update

    - by Dave
    In a prior blog entry I noted that Solaris used a "maximum dispersal" placement policy to assign nascent threads to their initial processors. The general idea is that threads should be placed as far away from each other as possible in the resource topology in order to reduce resource contention between concurrently running threads. This policy assumes that resource contention -- pipelines, memory channel contention, destructive interference in the shared caches, etc -- will likely outweigh (a) any potential communication benefits we might achieve by packing our threads more densely onto a subset of the NUMA nodes, and (b) benefits of NUMA affinity between memory allocated by one thread and accessed by other threads. We want our threads spread widely over the system and not packed together. Conceptually, when placing a new thread, the kernel picks the least loaded node NUMA node (the node with lowest aggregate load average), and then the least loaded core on that node, etc. Furthermore, the kernel places threads onto resources -- sockets, cores, pipelines, etc -- without regard to the thread's process membership. That is, initial placement is process-agnostic. Keep reading, though. This description is incorrect. On Solaris 10 on a SPARC T5440 with 4 x T2+ NUMA nodes, if the system is otherwise unloaded and we launch a process that creates 20 compute-bound concurrent threads, then typically we'll see a perfect balance with 5 threads on each node. We see similar behavior on an 8-node x86 x4800 system, where each node has 8 cores and each core is 2-way hyperthreaded. So far so good; this behavior seems in agreement with the policy I described in the 1st paragraph. I recently tried the same experiment on a 4-node T4-4 running Solaris 11. Both the T5440 and T4-4 are 4-node systems that expose 256 logical thread contexts. To my surprise, all 20 threads were placed onto just one NUMA node while the other 3 nodes remained completely idle. I checked the usual suspects such as processor sets inadvertently left around by colleagues, processors left offline, and power management policies, but the system was configured normally. I then launched multiple concurrent instances of the process, and, interestingly, all the threads from the 1st process landed on one node, all the threads from the 2nd process landed on another node, and so on. This happened even if I interleaved thread creating between the processes, so I was relatively sure the effect didn't related to thread creation time, but rather that placement was a function of process membership. I this point I consulted the Solaris sources and talked with folks in the Solaris group. The new Solaris 11 behavior is intentional. The kernel is no longer using a simple maximum dispersal policy, and thread placement is process membership-aware. Now, even if other nodes are completely unloaded, the kernel will still try to pack new threads onto the home lgroup (socket) of the primordial thread until the load average of that node reaches 50%, after which it will pick the next least loaded node as the process's new favorite node for placement. On the T4-4 we have 64 logical thread contexts (strands) per socket (lgroup), so if we launch 48 concurrent threads we will find 32 placed on one node and 16 on some other node. If we launch 64 threads we'll find 32 and 32. That means we can end up with our threads clustered on a small subset of the nodes in a way that's quite different that what we've seen on Solaris 10. So we have a policy that allows process-aware packing but reverts to spreading threads onto other nodes if a node becomes too saturated. It turns out this policy was enabled in Solaris 10, but certain bugs suppressed the mixed packing/spreading behavior. There are configuration variables in /etc/system that allow us to dial the affinity between nascent threads and their primordial thread up and down: see lgrp_expand_proc_thresh, specifically. In the OpenSolaris source code the key routine is mpo_update_tunables(). This method reads the /etc/system variables and sets up some global variables that will subsequently be used by the dispatcher, which calls lgrp_choose() in lgrp.c to place nascent threads. Lgrp_expand_proc_thresh controls how loaded an lgroup must be before we'll consider homing a process's threads to another lgroup. Tune this value lower to have it spread your process's threads out more. To recap, the 'new' policy is as follows. Threads from the same process are packed onto a subset of the strands of a socket (50% for T-series). Once that socket reaches the 50% threshold the kernel then picks another preferred socket for that process. Threads from unrelated processes are spread across sockets. More precisely, different processes may have different preferred sockets (lgroups). Beware that I've simplified and elided details for the purposes of explication. The truth is in the code. Remarks: It's worth noting that initial thread placement is just that. If there's a gross imbalance between the load on different nodes then the kernel will migrate threads to achieve a better and more even distribution over the set of available nodes. Once a thread runs and gains some affinity for a node, however, it becomes "stickier" under the assumption that the thread has residual cache residency on that node, and that memory allocated by that thread resides on that node given the default "first-touch" page-level NUMA allocation policy. Exactly how the various policies interact and which have precedence under what circumstances could the topic of a future blog entry. The scheduler is work-conserving. The x4800 mentioned above is an interesting system. Each of the 8 sockets houses an Intel 7500-series processor. Each processor has 3 coherent QPI links and the system is arranged as a glueless 8-socket twisted ladder "mobius" topology. Nodes are either 1 or 2 hops distant over the QPI links. As an aside the mapping of logical CPUIDs to physical resources is rather interesting on Solaris/x4800. On SPARC/Solaris the CPUID layout is strictly geographic, with the highest order bits identifying the socket, the next lower bits identifying the core within that socket, following by the pipeline (if present) and finally the logical thread context ("strand") on the core. But on Solaris on the x4800 the CPUID layout is as follows. [6:6] identifies the hyperthread on a core; bits [5:3] identify the socket, or package in Intel terminology; bits [2:0] identify the core within a socket. Such low-level details should be of interest only if you're binding threads -- a bad idea, the kernel typically handles placement best -- or if you're writing NUMA-aware code that's aware of the ambient placement and makes decisions accordingly. Solaris introduced the so-called critical-threads mechanism, which is expressed by putting a thread into the FX scheduling class at priority 60. The critical-threads mechanism applies to placement on cores, not on sockets, however. That is, it's an intra-socket policy, not an inter-socket policy. Solaris 11 introduces the Power Aware Dispatcher (PAD) which packs threads instead of spreading them out in an attempt to be able to keep sockets or cores at lower power levels. Maximum dispersal may be good for performance but is anathema to power management. PAD is off by default, but power management polices constitute yet another confounding factor with respect to scheduling and dispatching. If your threads communicate heavily -- one thread reads cache lines last written by some other thread -- then the new dense packing policy may improve performance by reducing traffic on the coherent interconnect. On the other hand if your threads in your process communicate rarely, then it's possible the new packing policy might result on contention on shared computing resources. Unfortunately there's no simple litmus test that says whether packing or spreading is optimal in a given situation. The answer varies by system load, application, number of threads, and platform hardware characteristics. Currently we don't have the necessary tools and sensoria to decide at runtime, so we're reduced to an empirical approach where we run trials and try to decide on a placement policy. The situation is quite frustrating. Relatedly, it's often hard to determine just the right level of concurrency to optimize throughput. (Understanding constructive vs destructive interference in the shared caches would be a good start. We could augment the lines with a small tag field indicating which strand last installed or accessed a line. Given that, we could augment the CPU with performance counters for misses where a thread evicts a line it installed vs misses where a thread displaces a line installed by some other thread.)

    Read the article

  • wpf exit thread automatically when application closes

    - by toni
    Hi, I have a main wpf window and one of its controls is a user control that I have created. this user control is an analog clock and contains a thread that update hour, minute and second hands. Initially it wasn't a thread, it was a timer event that updated the hour, minutes and seconds but I have changed it to a thread because the application do some hard work when the user press a start button and then the clock don't update so I changed it to a thread. COde snippet of wpf window: <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:GParts" xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes assembly=PresentationFramework.Aero" xmlns:UC="clr-namespace:GParts.UserControls" x:Class="GParts.WinMain" Title="GParts" WindowState="Maximized" Closing="Window_Closing" Icon="/Resources/Calendar-clock.png" x:Name="WMain" > <...> <!-- this is my user control --> <UC:AnalogClock Grid.Row="1" x:Name="AnalogClock" Background="Transparent" Margin="0" Height="Auto" Width="Auto"/> <...> </Window> My problem is when the user exits the application then the thread seems to continue executing. I would like the thread finishes automatically when main windows closes. code snippet of user control constructor: namespace GParts.UserControls { /// <summary> /// Lógica de interacción para AnalogClock.xaml /// </summary> public partial class AnalogClock : UserControl { System.Timers.Timer timer = new System.Timers.Timer(1000); public AnalogClock() { InitializeComponent(); MDCalendar mdCalendar = new MDCalendar(); DateTime date = DateTime.Now; TimeZone time = TimeZone.CurrentTimeZone; TimeSpan difference = time.GetUtcOffset(date); uint currentTime = mdCalendar.Time() + (uint)difference.TotalSeconds; christianityCalendar.Content = mdCalendar.Date("d/e/Z", currentTime, false); // this was before implementing thread //timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); //timer.Enabled = true; // The Work to perform ThreadStart start = delegate() { // With this condition the thread exits when main window closes but // despite of this it seems like the thread continues executing after // exiting application because in task manager cpu is very busy // while ((this.IsInitialized) && (this.Dispatcher.HasShutdownFinished== false)) { this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { DateTime hora = DateTime.Now; secondHand.Angle = hora.Second * 6; minuteHand.Angle = hora.Minute * 6; hourHand.Angle = (hora.Hour * 30) + (hora.Minute * 0.5); DigitalClock.CurrentTime = hora; })); } Console.Write("Quit ok"); }; // Create the thread and kick it started! new Thread(start).Start(); } // this was before implementing thread void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { DateTime hora = DateTime.Now; secondHand.Angle = hora.Second * 6; minuteHand.Angle = hora.Minute * 6; hourHand.Angle = (hora.Hour * 30) + (hora.Minute * 0.5); DigitalClock.CurrentTime = hora; })); } } // end class } // end namespace How can I exit correctly from thread automatically when main window closes and then application exits? Thanks very much!

    Read the article

  • In .NET when Aborting Thread, can this piece of code get corrupted?

    - by bosko
    Little intro: In complex multithreaded aplication (enterprise service bus EBS), I need to use Thread.Abort, because this EBS accepts user written modules which communicates with hardware security modules. So if this module gets deadlocked or hardware stops responding - i need to just unload this module and rest of this server aplication must keep runnnig. So there is abort sync mechanism which ensures that code can be aborted only in user section and this section must be marked as AbortAble. If this happen there is possibility that ThreadAbortException will be thrown in this pieace of code: public void StopAbortSection() { var id = Thread.CurrentThread.ManagedThreadId; lock (threadIdMap[id]) { .... } } If module is on AbortSection and Aplication decides to abort module, but after this decision but before actual Thread.Abort, module enters NonAbortableSection by calling this method, but lock is actualy taken on that locking object. So lock will block until Abort or abort can be executed before reaching this block by this code. But Object with this method is essential and i need to be sure that this pieace of code is safe to abort in any moment. Probably i have to mention that threadIdMap is Dictionary(int,ManualResetEvent), so locking object is instance of ManualResetEvent. I hope you now understad my question. Sorry for its largeness.

    Read the article

  • Stopping work from one thread using another thread

    - by 113483626144458436514
    Not sure if my title is worded well, but whatever :) I have two threads: the main thread with the work that needs to be done, and a worker thread that contains a form with a progress bar and a cancel button. In normal code, it would be the other way around, but I can't do that in this case. When the user clicks the cancel button, a prompt is displayed asking if he wants to really cancel the work. The problem is that work continues on the main thread. I can get the main thread to stop work and such, but I would like for it to stop doing work when he clicks "Yes" on the prompt. Example: // Main thread work starts here t1 = new Thread(new ThreadStart(progressForm_Start)); t1.Start(); // Working for (i = 0; i <= 10000; i++) { semaphore.WaitOne(); if (pBar.Running) bgworker_ProgressChanged(i); semaphore.Release(); if (pBar.IsCancelled) break; } t1.Abort(); // Main thread work ends here // Start progress bar form in another thread void progressForm_Start() { pBar.Status("Starting"); pBar.ShowDialog(); } I could theoretically include a prompt in the cancelWatch() function, but then I would have to do that everywhere I'm implementing this class.

    Read the article

  • wrapping boost::ublas with swig

    - by leon
    I am trying to pass data around the numpy and boost::ublas layers. I have written an ultra thin wrapper because swig cannot parse ublas' header correctly. The code is shown below #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/lexical_cast.hpp> #include <algorithm> #include <sstream> #include <string> using std::copy; using namespace boost; typedef boost::numeric::ublas::matrix<double> dm; typedef boost::numeric::ublas::vector<double> dv; class dvector : public dv{ public: dvector(const int rhs):dv(rhs){;}; dvector(); dvector(const int size, double* ptr):dv(size){ copy(ptr, ptr+sizeof(double)*size, &(dv::data()[0])); } ~dvector(){} }; with the SWIG interface that looks something like %apply(int DIM1, double* INPLACE_ARRAY1) {(const int size, double* ptr)} class dvector{ public: dvector(const int rhs); dvector(); dvector(const int size, double* ptr); %newobject toString; char* toString(); ~dvector(); }; I have compiled them successfully via gcc 4.3 and vc++9.0. However when I simply run a = dvector(array([1.,2.,3.])) it gives me a segfault. This is the first time I use swigh with numpy and not have fully understanding between the data conversion and memory buffer passing. Does anyone see something obvious I have missed? I have tried to trace through with a debugger but it crashed within the assmeblys of python.exe. I have no clue if this is a swig problem or of my simple wrapper. Anything is appreciated.

    Read the article

  • I just can't kill Java thread.

    - by Adrian
    I have a thread that downloads some images from internet using different proxies. Sometimes it hangs, and can't be killed by any means. public HttpURLConnection uc; public InputStream in; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("server", 8080)); URL url = new URL("http://images.com/image.jpg"); uc = (HttpURLConnection)url.openConnection(proxy); uc.setConnectTimeout(30000); uc.setAllowUserInteraction(false); uc.setDoOutput(true); uc.addRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); uc.connect(); in = uc.getInputStream(); When it hangs, it freezes at the uc.getInputStream() method. I made a timer which tries to kill the thread if it's run time exceeds 3 minutes. I tried .terminate() the thread. No effect. I tried uc.disconnect() from the main thread. The method also hangs and with it, the main thread. I tried in.close(). No effect. I tried uc=null, in=null hoping for an exception that will end the thread. It keeps running. It never passes the uc.getInputStream() method. In my last test the thread lasted over 14 hours after receiving all above commands (or various combinations). I had to kill the Java process to stop the thread. If I just ignore the thread, and set it's instance to null, the thread doesn't die and is not cleaned by garbage collector. I know that because if I let the application running for several days, the Java process takes more and more system memory. In 3 days it took 10% of my 8Gb. RAM system. It is impossible to kill a thread whatever?

    Read the article

  • Is it a good way to close a thread?

    - by Roman
    I have a short version of the question: I start a thread like that: counter.start();, where counter is a thread. At the point when I want to stop the thread I do that: counter.interrupt() In my thread I periodically do this check: Thread.interrupted(). If it gives true I return from the thread and, as a consequence, it stops. And here are some details, if needed: If you need more details, they are here. From the invent dispatch thread I start a counter thread in this way: public static void start() { SwingUtilities.invokeLater(new Runnable() { public void run() { showGUI(); counter.start(); } }); } where the thread is defined like that: public static Thread counter = new Thread() { public void run() { for (int i=4; i>0; i=i-1) { updateGUI(i,label); try {Thread.sleep(1000);} catch(InterruptedException e) {}; } // The time for the partner selection is over. SwingUtilities.invokeLater(new Runnable() { public void run() { frame.remove(partnerSelectionPanel); frame.add(selectionFinishedPanel); frame.invalidate(); frame.validate(); } }); } }; The thread performs countdown in the "first" window (it shows home much time left). If time limit is over, the thread close the "first" window and generate a new one. I want to modify my thread in the following way: public static Thread counter = new Thread() { public void run() { for (int i=4; i>0; i=i-1) { if (!Thread.interrupted()) { updateGUI(i,label); } else { return; } try {Thread.sleep(1000);} catch(InterruptedException e) {}; } // The time for the partner selection is over. if (!Thread.interrupted()) { SwingUtilities.invokeLater(new Runnable() { public void run() { frame.remove(partnerSelectionPanel); frame.add(selectionFinishedPanel); frame.invalidate(); frame.validate(); } }); } else { return; } } };

    Read the article

  • Why boost property tree write_json saves everything as string? Is it possible to change that?

    - by pprzemek
    I'm trying to serialize using boost property tree write_json, it saves everything as strings, it's not that data are wrong, but I need to cast them explicitly every time and I want to use them somewhere else. (like in python or other C++ json (non boost) library) here is some sample code and what I get depending on locale: boost::property_tree::ptree root, arr, elem1, elem2; elem1.put<int>("key0", 0); elem1.put<bool>("key1", true); elem2.put<float>("key2", 2.2f); elem2.put<double>("key3", 3.3); arr.push_back( std::make_pair("", elem1) ); arr.push_back( std::make_pair("", elem2) ); root.put_child("path1.path2", arr); std::stringstream ss; write_json(ss, root); std::string my_string_to_send_somewhare_else = ss.str(); and my_string_to_send_somewhere_else is sth. like this: { "path1" : { "path2" : [ { "key0" : "0", "key1" : "true" }, { "key2" : "2.2", "key3" : "3.3" } ] } } Is there anyway to save them as the values, like: "key1" : true or "key2" : 2.2 ?

    Read the article

  • Intel turbo boost - in reality

    - by gisek
    I have an Intel i7-3630QM processor in my laptop. Its speed is supposed to be from 2.4 to 3.4 GHz in turbo boost mode. In reality, will it ever run all cores on full speed (3.4GHz mentioned above) at the same time? I heard somewhere that this additional 1GHz is shared between all cores in laptops. If the boost is 1GHz per core it's pretty impressive (over 40% speed up). What does it really look like? How long can a processor run in turbo mode?

    Read the article

  • Who interrupts my thread?

    - by Thirler
    I understand what an InterruptedException does and why it is thrown. However in my application I get it when waiting for SwingUtilities.invokeAndWait() on a thread that is only known by my application, and my application never class Thread.interrupt() on any thread, also it never passes the reference of the thread on to anyone. So my question is: Who interrupts my thread? Is there any way to tell? Is there a reason why the InterruptedException doesn't contain the name of the Thread that requests the interrupt? I read that it could be a framework or library that does this, we use the following, but I can't think of reason for them to interrupt my thread: Hibernate Spring Log4J Mysql connector

    Read the article

  • Using a Cross Thread Boolean to Abort Thread

    - by Jon
    Possible Duplicate: Can a C# thread really cache a value and ignore changes to that value on other threads? Lets say we have this code: bool KeepGoing = true; DataInThread = new Thread(new ThreadStart(DataInThreadMethod)); DataInThread.Start(); //bla bla time goes on KeepGoing = false; private void DataInThreadMethod() { while (KeepGoing) { //Do stuff } } } Now the idea is that using the boolean is a safe way to terminate the thread however because that boolean exists on the calling thread does that cause any issue? That boolean is only used on the calling thread to stop the thread so its not like its being used elsewhere

    Read the article

  • Handle leaks with .NET System.Threading.Thread class

    - by Mahno
    I've a problem that number of Handles in my app is continuously growing. I did the debugging and recognize that this is caused by System.Threading.Thread class which is used for some routine. To simplify the debugging I’ve created a sample .NET application: ... private void button1_Click(object sender, EventArgs e) { Thread t = new Thread(DoWork); t.Start(); } public void DoWork(object parameter) { // Do something... } ... Each time I’m clicking the button, a thread is created using System.Threading.Thread class. The problem is that looks like the thread do not frees Handles because each click cause number of Handles growing by ~5. The question is: how can I manually free all Handles created by System.Threading.Thread class? Thanks in advance.

    Read the article

  • Run sub on main thread from separate thread [VB.NET|SerialPort]

    - by Steven
    I'm reading data from a serial port, but the DataReceived event of SerialPort is handled on it's own thread. I want to handle this on the main thread, but simply declaring an event and raising it still results in it being processed on the SerialPort thread. I'm assuming I need to declare a delegate I can call, but I don't see how that would work. For example, I want to call Sub HandleDataReceived() on the main thread from the DataReceived thread, having HandleDataReceived() run on the main thread. How would I do this?

    Read the article

  • Rails: Thread won't affect database unless joined to main Thread

    - by hatboysam
    I have a background operation I would like to occur every 20 seconds in Rails given that some condition is true. It kicked off when a certain controller route is hit, and it looks like this def startProcess argId = self.id t = Thread.new do while (Argument.isRunning(argId)) do Argument.update(argId) Argument.markVotes(argId) puts "Thread ran" sleep 20 end end end However, this code does absolutely nothing to my database unless I call "t.join" in which case my whole server is blocked for a long time (but it works). Why can't the read commit ActiveRecords without being joined to the main thread? The thread calls methods that look something like def sample model = Model.new() model.save() end but the models are not saved to the DB unless the thread is joined to the main thread. Why is this? I have been banging my head about this for hours.

    Read the article

  • Re: Help with Boost Grammar

    - by Decmac04
    I have redesigned and extended the grammar I asked about earlier as shown below: // BIFAnalyser.cpp : Defines the entry point for the console application. // // /*============================================================================= Copyright (c) Temitope Jos Onunkun 2010 http://www.dcs.kcl.ac.uk/pg/onun/ Use, modification and distribution is subject to the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ //////////////////////////////////////////////////////////////////////////// // // // B Machine parser using the Boost "Grammar" and "Semantic Actions". // // // //////////////////////////////////////////////////////////////////////////// include include include include include include //////////////////////////////////////////////////////////////////////////// using namespace std; using namespace boost::spirit; //////////////////////////////////////////////////////////////////////////// // // Semantic Actions // //////////////////////////////////////////////////////////////////////////// // // namespace { //semantic action function on individual lexeme void do_noint(char const* start, char const* end) { string str(start, end); if (str != "NAT1") cout << "PUSH(" << str << ')' << endl; } //semantic action function on addition of lexemes void do_add(char const*, char const*) { cout << "ADD" << endl; // for(vector::iterator vi = strVect.begin(); vi < strVect.end(); ++vi) // cout << *vi << " "; } //semantic action function on subtraction of lexemes void do_subt(char const*, char const*) { cout << "SUBTRACT" << endl; } //semantic action function on multiplication of lexemes void do_mult(char const*, char const*) { cout << "\nMULTIPLY" << endl; } //semantic action function on division of lexemes void do_div(char const*, char const*) { cout << "\nDIVIDE" << endl; } // // vector flowTable; //semantic action function on simple substitution void do_sSubst(char const* start, char const* end) { string str(start, end); //use boost tokenizer to break down tokens typedef boost::tokenizer Tokenizer; boost::char_separator sep(" -+/*:=()",0,boost::drop_empty_tokens); // char separator definition Tokenizer tok(str, sep); Tokenizer::iterator tok_iter = tok.begin(); pair dependency; //create a pair object for dependencies //create a vector object to store all tokens vector dx; // int counter = 0; // tracks token position for(tok.begin(); tok_iter != tok.end(); ++tok_iter) //save all tokens in vector { dx.push_back(*tok_iter ); } counter = dx.size(); // vector d_hat; //stores set of dependency pairs string dep; //pairs variables as string object // dependency.first = *tok.begin(); vector FV; for(int unsigned i=1; i < dx.size(); i++) { // if(!atoi(dx.at(i).c_str()) && (dx.at(i) !=" ")) { dependency.second = dx.at(i); dep = dependency.first + "|-" + dependency.second + " "; d_hat.push_back(dep); vector<string> row; row.push_back(dependency.first); //push x_hat into first column of each row for(unsigned int j=0; j<2; j++) { row.push_back(dependency.second);//push an element (column) into the row } flowTable.push_back(row); //Add the row to the main vector } } //displays internal representation of information flow table cout << "\n****************\nDependency Table\n****************\n"; cout << "X_Hat\tDx\tG_Hat\n"; cout << "-----------------------------\n"; for(unsigned int i=0; i < flowTable.size(); i++) { for(unsigned int j=0; j<2; j++) { cout << flowTable[i][j] << "\t "; } if (*tok.begin() != "WHILE" ) //if there are no global flows, cout << "\t{}"; //display empty set cout << "\n"; } cout << "***************\n\n"; for(int unsigned j=0; j < FV.size(); j++) { if(FV.at(j) != dependency.second) dep = dependency.first + "|-" + dependency.second + " "; d_hat.push_back(dep); } cout << "PUSH(" << str << ')' << endl; cout << "\n*******\nDependency pairs\n*******\n"; for(int unsigned i=0; i < d_hat.size(); i++) cout << d_hat.at(i) << "\n...\n"; cout << "\nSIMPLE SUBSTITUTION\n\n"; } //semantic action function on multiple substitution void do_mSubst(char const* start, char const* end) { string str(start, end); cout << "PUSH(" << str << ')' << endl; //cout << "\nMULTIPLE SUBSTITUTION\n\n"; } //semantic action function on unbounded choice substitution void do_mChoice(char const* start, char const* end) { string str(start, end); cout << "PUSH(" << str << ')' << endl; cout << "\nUNBOUNDED CHOICE SUBSTITUTION\n\n"; } void do_logicExpr(char const* start, char const* end) { string str(start, end); //use boost tokenizer to break down tokens typedef boost::tokenizer Tokenizer; boost::char_separator sep(" -+/*=:()<",0,boost::drop_empty_tokens); // char separator definition Tokenizer tok(str, sep); Tokenizer::iterator tok_iter = tok.begin(); //pair dependency; //create a pair object for dependencies //create a vector object to store all tokens vector dx; for(tok.begin(); tok_iter != tok.end(); ++tok_iter) //save all tokens in vector { dx.push_back(*tok_iter ); } for(unsigned int i=0; i cout << "PUSH(" << str << ')' << endl; cout << "\nPREDICATE\n\n"; } void do_predicate(char const* start, char const* end) { string str(start, end); cout << "PUSH(" << str << ')' << endl; cout << "\nMULTIPLE PREDICATE\n\n"; } void do_ifSelectPre(char const* start, char const* end) { string str(start, end); //if cout << "PUSH(" << str << ')' << endl; cout << "\nPROTECTED SUBSTITUTION\n\n"; } //semantic action function on machine substitution void do_machSubst(char const* start, char const* end) { string str(start, end); cout << "PUSH(" << str << ')' << endl; cout << "\nMACHINE SUBSTITUTION\n\n"; } } //////////////////////////////////////////////////////////////////////////// // // Machine Substitution Grammar // //////////////////////////////////////////////////////////////////////////// // Simple substitution grammar parser with integer values removed struct Substitution : public grammar { template struct definition { definition(Substitution const& ) { machine_subst = ( (simple_subst) | (multi_subst) | (if_select_pre_subst) | (unbounded_choice) )[&do_machSubst] ; unbounded_choice = str_p("ANY") ide_list str_p("WHERE") predicate str_p("THEN") machine_subst str_p("END") ; if_select_pre_subst = ( ( str_p("IF") predicate str_p("THEN") machine_subst *( str_p("ELSIF") predicate machine_subst ) !( str_p("ELSE") machine_subst) str_p("END") ) | ( str_p("SELECT") predicate str_p("THEN") machine_subst *( str_p("WHEN") predicate machine_subst ) !( str_p("ELSE") machine_subst) str_p("END")) | ( str_p("PRE") predicate str_p("THEN") machine_subst str_p("END") ) )[&do_ifSelectPre] ; multi_subst = ( (machine_subst) *( ( str_p("||") (machine_subst) ) | ( str_p("[]") (machine_subst) ) ) ) [&do_mSubst] ; simple_subst = (identifier str_p(":=") arith_expr) [&do_sSubst] ; expression = predicate | arith_expr ; predicate = ( (logic_expr) *( ( ch_p('&') (logic_expr) ) | ( str_p("OR") (logic_expr) ) ) )[&do_predicate] ; logic_expr = ( identifier (str_p("<") arith_expr) | (str_p("<") arith_expr) | (str_p("/:") arith_expr) | (str_p("<:") arith_expr) | (str_p("/<:") arith_expr) | (str_p("<<:") arith_expr) | (str_p("/<<:") arith_expr) | (str_p("<=") arith_expr) | (str_p("=") arith_expr) | (str_p("=") arith_expr) | (str_p("=") arith_expr) ) [&do_logicExpr] ; arith_expr = term *( ('+' term)[&do_add] | ('-' term)[&do_subt] ) ; term = factor ( ('' factor)[&do_mult] | ('/' factor)[&do_div] ) ; factor = lexeme_d[( identifier | +digit_p)[&do_noint]] | '(' expression ')' | ('+' factor) ; ide_list = identifier *( ch_p(',') identifier ) ; identifier = alpha_p +( alnum_p | ch_p('_') ) ; } rule machine_subst, unbounded_choice, if_select_pre_subst, multi_subst, simple_subst, expression, predicate, logic_expr, arith_expr, term, factor, ide_list, identifier; rule<ScannerT> const& start() const { return predicate; //return multi_subst; //return machine_subst; } }; }; //////////////////////////////////////////////////////////////////////////// // // Main program // //////////////////////////////////////////////////////////////////////////// int main() { cout << "*********************************\n\n"; cout << "\t\t...Machine Parser...\n\n"; cout << "*********************************\n\n"; // cout << "Type an expression...or [q or Q] to quit\n\n"; string str; int machineCount = 0; char strFilename[256]; //file name store as a string object do { cout << "Please enter a filename...or [q or Q] to quit:\n\n "; //prompt for file name to be input //char strFilename[256]; //file name store as a string object cin strFilename; if(*strFilename == 'q' || *strFilename == 'Q') //termination condition return 0; ifstream inFile(strFilename); // opens file object for reading //output file for truncated machine (operations only) if (inFile.fail()) cerr << "\nUnable to open file for reading.\n" << endl; inFile.unsetf(std::ios::skipws); Substitution elementary_subst; // Simple substitution parser object string next; while (inFile str) { getline(inFile, next); str += next; if (str.empty() || str[0] == 'q' || str[0] == 'Q') break; parse_info< info = parse(str.c_str(), elementary_subst !end_p, space_p); if (info.full) { cout << "\n-------------------------\n"; cout << "Parsing succeeded\n"; cout << "\n-------------------------\n"; } else { cout << "\n-------------------------\n"; cout << "Parsing failed\n"; cout << "stopped at: " << info.stop << "\"\n"; cout << "\n-------------------------\n"; } } } while ( (*strFilename != 'q' || *strFilename !='Q')); return 0; } However, I am experiencing the following unexpected behaviours on testing: The text files I used are: f1.txt, ... containing ...: debt:=(LoanRequest+outstandingLoan1)*20 . f2.txt, ... containing ...: debt:=(LoanRequest+outstandingLoan1)*20 || newDebt := loanammount-paidammount || price := purchasePrice + overhead + bb . f3.txt, ... containing ...: yy < (xx+7+ww) . f4.txt, ... containing ...: yy < (xx+7+ww) & yy : NAT . When I use multi_subst as start rule both files (f1 and f2) are parsed correctly; When I use machine_subst as start rule file f1 parse correctly, while file f2 fails, producing the error: “Parsing failed stopped at: || newDebt := loanammount-paidammount || price := purchasePrice + overhead + bb” When I use predicate as start symbol, file f3 parse correctly, but file f4 yields the error: “ “Parsing failed stopped at: & yy : NAT” Can anyone help with the grammar, please? It appears there are problems with the grammar that I have so far been unable to spot.

    Read the article

  • What header file is where the boost libray define its own primitive data type?

    - by ronghai
    Recently, I try to use the boost::spirit::qi binary endian parser to parse some binary data depends on the endianness of the Platform. There is a simple example, like following: Using declarations and variables: using boost::spirit::qi::little_word; using boost::spirit::qi::little_dword; using boost::spirit::qi::little_qword; boost::uint16_t us; boost::uint32_t ui; boost::uint64_t ul; Basic usage of the little endian binary parsers: test_parser_attr("\x01\x02", little_word, us); assert(us == 0x0201); test_parser_attr("\x01\x02\x03\x04", little_dword, ui); assert(ui == 0x04030201); test_parser_attr("\x01\x02\x03\x04\x05\x06\x07\x08", little_qword, ul); assert(ul == 0x0807060504030201LL); test_parser("\x01\x02", little_word(0x0201)); test_parser("\x01\x02\x03\x04", little_dword(0x04030201)); test_parser("\x01\x02\x03\x04\x05\x06\x07\x08", little_qword(0x0807060504030201LL)); It works very well. But my questions come, why do we need use some data types like boost::uint16_t, boost::uint32_t here? Can I use unsigned long or unsigned int here? And if I want to parse double or float data type, what boost data type should I use? And please tell me where is boost define the above these types? Thanks a lot.

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >