Search Results

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

Page 4/389 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • C++ boost thread reusing threads

    - by aaa
    hi. I am trying to accomplish something like this: thread t; // create/initialize thread t.launch(); // launch thread. t.wait(); // wait t.launch(); // relaunch the same thread How to go about implementing something like this using boost threads? in essence, I need persistent relaunch-able thread. Thanks

    Read the article

  • Thread.Interrupt Is Evil

    - by Alois Kraus
    Recently I have found an interesting issue with Thread.Interrupt during application shutdown. Some application was crashing once a week and we had not really a clue what was the issue. Since it happened not very often it was left as is until we have got some memory dumps during the crash. A memory dump usually means WindDbg which I really like to use (I know I am one of the very few fans of it).  After a quick analysis I did find that the main thread already had exited and the thread with the crash was stuck in a Monitor.Wait. Strange Indeed. Running the application a few thousand times under the debugger would potentially not have shown me what the reason was so I decided to what I call constructive debugging. I did create a simple Console application project and try to simulate the exact circumstances when the crash did happen from the information I have via memory dump and source code reading. The thread that was  crashing was actually MS code from an old version of the Microsoft Caching Application Block. From reading the code I could conclude that the main thread did call the Dispose method on the CacheManger class which did call Thread.Interrupt on the cache scavenger thread which was just waiting for work to do. My first version of the repro looked like this   static void Main(string[] args) { Thread t = new Thread(ThreadFunc) { IsBackground = true, Name = "Test Thread" }; t.Start(); Console.WriteLine("Interrupt Thread"); t.Interrupt(); } static void ThreadFunc() { while (true) { object value = Dequeue(); // block until unblocked or awaken via ThreadInterruptedException } } static object WaitObject = new object(); static object Dequeue() { object lret = "got value"; try { lock (WaitObject) { } } catch (ThreadInterruptedException) { Console.WriteLine("Got ThreadInterruptException"); lret = null; } return lret; } I do start a background thread and call Thread.Interrupt on it and then directly let the application terminate. The thread in the meantime does plenty of Monitor.Enter/Leave calls to simulate work on it. This first version did not crash. So I need to dig deeper. From the memory dump I did know that the finalizer thread was doing just some critical finalizers which were closing file handles. Ok lets add some long running finalizers to the sample. class FinalizableObject : CriticalFinalizerObject { ~FinalizableObject() { Console.WriteLine("Hi we are waiting to finalize now and block the finalizer thread for 5s."); Thread.Sleep(5000); } } class Program { static void Main(string[] args) { FinalizableObject fin = new FinalizableObject(); Thread t = new Thread(ThreadFunc) { IsBackground = true, Name = "Test Thread" }; t.Start(); Console.WriteLine("Interrupt Thread"); t.Interrupt(); GC.KeepAlive(fin); // prevent finalizing it too early // After leaving main the other thread is woken up via Thread.Abort // while we are finalizing. This causes a stackoverflow in the CLR ThreadAbortException handling at this time. } With this changed Main method and a blocking critical finalizer I did get my crash just like the real application. The funny thing is that this is actually a CLR bug. When the main method is left the CLR does suspend all threads except the finalizer thread and declares all objects as garbage. After the normal finalizers were called the critical finalizers are executed to e.g. free OS handles (usually). Remember that I did call Thread.Interrupt as one of the last methods in the Main method. The Interrupt method is actually asynchronous and does wake a thread up and throws a ThreadInterruptedException only once unlike Thread.Abort which does rethrow the exception when an exception handling clause is left. It seems that the CLR does not expect that a frozen thread does wake up again while the critical finalizers are executed. While trying to raise a ThreadInterrupedException the CLR goes down with an stack overflow. Ups not so nice. Why has this nobody noticed for years is my next question. As it turned out this error does only happen on the CLR for .NET 4.0 (x86 and x64). It does not show up in earlier or later versions of the CLR. I have reported this issue on connect here but so far it was not confirmed as a CLR bug. But I would be surprised if my console application was to blame for a stack overflow in my test thread in a Monitor.Wait call. What is the moral of this story? Thread.Abort is evil but Thread.Interrupt is too. It is so evil that even the CLR of .NET 4.0 contains a race condition during the CLR shutdown. When the CLR gurus can get it wrong the chances are high that you get it wrong too when you use this constructs. If you do not believe me see what Patrick Smacchia does blog about Thread.Abort and List.Sort. Not only the CLR creators can get it wrong. The BCL writers do sometimes have a hard time with correct exception handling as well. If you do tell me that you use Thread.Abort frequently and never had problems with it I do suspect that you do not have looked deep enough into your application to find such sporadic errors.

    Read the article

  • Does boost::asio makes excessive small heap allocations or am I wrong?

    - by Poni
    #include <cstdlib> #include <iostream> #include <boost/bind.hpp> #include <boost/asio.hpp> using boost::asio::ip::tcp; class session { public: session(boost::asio::io_service& io_service) : socket_(io_service) { } tcp::socket& socket() { return socket_; } void start() { socket_.async_read_some(boost::asio::buffer(data_, max_length - 1), boost::bind(&session::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void handle_read(const boost::system::error_code& error, size_t bytes_transferred) { if (!error) { data_[bytes_transferred] = '\0'; if(NULL != strstr(data_, "quit")) { this->socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both); this->socket().close(); // how to make this dispatch "handle_read()" with a "disconnected" flag? } else { boost::asio::async_write(socket_, boost::asio::buffer(data_, bytes_transferred), boost::bind(&session::handle_write, this, boost::asio::placeholders::error)); socket_.async_read_some(boost::asio::buffer(data_, max_length - 1), boost::bind(&session::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } else { delete this; } } void handle_write(const boost::system::error_code& error) { if (!error) { // } else { delete this; } } private: tcp::socket socket_; enum { max_length = 1024 }; char data_[max_length]; }; class server { public: server(boost::asio::io_service& io_service, short port) : io_service_(io_service), acceptor_(io_service, tcp::endpoint(tcp::v4(), port)) { session* new_session = new session(io_service_); acceptor_.async_accept(new_session->socket(), boost::bind(&server::handle_accept, this, new_session, boost::asio::placeholders::error)); } void handle_accept(session* new_session, const boost::system::error_code& error) { if (!error) { new_session->start(); new_session = new session(io_service_); acceptor_.async_accept(new_session->socket(), boost::bind(&server::handle_accept, this, new_session, boost::asio::placeholders::error)); } else { delete new_session; } } private: boost::asio::io_service& io_service_; tcp::acceptor acceptor_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: async_tcp_echo_server <port>\n"; return 1; } boost::asio::io_service io_service; using namespace std; // For atoi. server s(io_service, atoi(argv[1])); io_service.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } While experimenting with boost::asio I've noticed that within the calls to async_write()/async_read_some() there is a usage of the C++ "new" keyword. Also, when stressing this echo server with a client (1 connection) that sends for example 100,000 times some data, the memory usage of this program is getting higher and higher. What's going on? Will it allocate memory for every call? Or am I wrong? Asking because it doesn't seem right that a server app will allocate, anything. Can I handle it, say with a memory pool? Another side-question: See the "this-socket().close();" ? I want it, as the comment right to it says, to dispatch that same function one last time, with a disconnection error. Need that to do some clean-up. How do I do that? Thank you all gurus (:

    Read the article

  • How to check if Thread finished execution

    - by user295502
    I have following problem: I want to check (C#) if thread has finished execution, i.e. if the thread method returned. What I do now is call Thread.Join(1), but this gives 1 ms delay. Is there any way to simply check if thread finished. Inspecting Thread.ThreadState just seems too cumbersome.

    Read the article

  • Boost::binary<> [c++][Boost]

    - by atch
    Hi, Is there anything in boost libraries like binary? For example I would like to write: binary<10101> a; I'm ashamed to admit that I've tried to find it (Google, Boost) but no results. They're mention something about binary_int< but I couldn't find neither if it is available nor what header file shall I include; Thanks for help.

    Read the article

  • Boost program will not working on Linux

    - by Martin Lauridsen
    Hi SOF, I have this program which uses Boost::Asio for sockets. I pretty much altered some code from the Boost examples. The program compiles and runs just like it should on Windows in VS. However, when I compile the program on Linux and run it, I get a Segmentation fault. I posted the code here The command I use to compile it is this: c++ -I/appl/htopopt/Linux_x86_64/NTL-5.4.2/include -I/appl/htopopt/Linux_x86_64/boost_1_43_0/include mpqs.cpp mpqs_polynomial.cpp mpqs_host.cpp -o mpqs_host -L/appl/htopopt/Linux_x86_64/NTL-5.4.2/lib -lntl -L/appl/htopopt/Linux_x86_64/gmp-4.2.1/lib -lgmp -lm -L/appl/htopopt/Linux_x86_64/boost_1_43_0/lib -lboost_system -lboost_thread -static -lpthread By commenting out code, I have found out that I get the Segmentation fault due to the following line: boost::asio::io_service io_service; Can anyone provide any assistance, as to what may be the problem (and the solution)? Thanks! Edit: I tried changing the program to a minimal example, using no other libraries or headers, just boost/asio.hpp: #define DEBUG 0 #include <boost/asio.hpp> int main(int argc, char* argv[]) { boost::asio::io_service io_service; return 0; } I also removed other library inclusions and linking on compilation, however this minimal example still gives me a segmentation fault.

    Read the article

  • Boost.Thread throws bad_alloc exception in VS2010

    - by the_drow
    Upon including <boost/thread.hpp> I get this exception: First-chance exception at 0x7c812afb in CSF.exe: Microsoft C++ exception: boost::exception_detail::clone_impl<boost::exception_detail::bad_alloc_> at memory location 0x0012fc3c.. First-chance exception at 0x7c812afb in CSF.exe: Microsoft C++ exception: [rethrow] at memory location 0x00000000.. I can't catch it, breaking at the memory location brings me to kernel32.dll and at this point I cannot say what's going on but it appears that the exception is thrown after the program ends and VS is capable of catching it. The testcase: #include <boost/thread.hpp> int main() { return 0; }

    Read the article

  • LibPNG + Boost::GIL: png_infopp_NULL not found

    - by Viet
    Hi, I always get this error when trying to compile my file with Boost::GIL PNG IO support: (I'm running Mac OS X Leopard and Boost 1.42, LibPNG 1.4) /usr/local/include/boost/gil/extension/io/png_io_private.hpp: In member function 'void boost::gil::detail::png_reader::init()': /usr/local/include/boost/gil/extension/io/png_io_private.hpp:155: error: 'png_infopp_NULL' was not declared in this scope /usr/local/include/boost/gil/extension/io/png_io_private.hpp:160: error: 'png_infopp_NULL' was not declared in this scope /usr/local/include/boost/gil/extension/io/png_io_private.hpp: In destructor 'boost::gil::detail::png_reader::~png_reader()': /usr/local/include/boost/gil/extension/io/png_io_private.hpp:174: error: 'png_infopp_NULL' was not declared in this scope /usr/local/include/boost/gil/extension/io/png_io_private.hpp: In member function 'void boost::gil::detail::png_reader::apply(const View&)': /usr/local/include/boost/gil/extension/io/png_io_private.hpp:186: error: 'int_p_NULL' was not declared in this scope /usr/local/include/boost/gil/extension/io/png_io_private.hpp: In member function 'void boost::gil::detail::png_reader_color_convert<CC>::apply(const View&)': /usr/local/include/boost/gil/extension/io/png_io_private.hpp:228: error: 'int_p_NULL' was not declared in this scope /usr/local/include/boost/gil/extension/io/png_io_private.hpp: In member function 'void boost::gil::detail::png_writer::init()': /usr/local/include/boost/gil/extension/io/png_io_private.hpp:317: error: 'png_infopp_NULL' was not declared in this scope

    Read the article

  • Problem Linking Boost Filesystem Library in Microsoft Visual C++

    - by Scott
    Hello. I am having trouble getting my project to link to the Boost (version 1.37.0) Filesystem lib file in Microsoft Visual C++ 2008 Express Edition. The Filesystem library is not a header-only library. I have been following the Getting Started on Windows guide posted on the official boost web page. Here are the steps I have taken: I used bjam to build the complete set of lib files using: bjam --build-dir="C:\Program Files\boost\build-boost" --toolset=msvc --build-type=complete I copied the /libs directory (located in C:\Program Files\boost\build-boost\boost\bin.v2) to C:\Program Files\boost\boost_1_37_0\libs. In Visual C++, under Project Properties Additional Library Directories I added these paths: C:\Program Files\boost\boost_1_37_0\libs C:\Program Files\boost\boost_1_37_0\libs\filesystem\build\msvc-9.0express\debug\link-static\threading-multi I added the second one out of desperation. It is the exact directory where libboost_system-vc90-mt-gd-1_37.lib resides. In Configuration Properties C/C++ General Additional Include Directories I added the following path: C:\Program Files\boost\boost_1_37_0 Then, to put the icing on the cake, under Tools Options VC++ Directories Library files, I added the same directories mentioned in step 3. Despite all this, when I build my project I get the following error: fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_37.lib' Additionally, here is the code that I am attempting to compile as well as a screen shot of the aformentioned directory where the (assumedly correct) lib file resides: #include "boost/filesystem.hpp" // includes all needed Boost.Filesystem declarations #include <iostream> // for std::cout using boost::filesystem; // for ease of tutorial presentation; // a namespace alias is preferred practice in real code using namespace std; int main() { cout << "Hello, world!" << endl; return 0; } Can anyone help me out? Let me know if you need to know anything else. As always, thanks in advance.

    Read the article

  • Synchronization between game logic thread and rendering thread

    - by user782220
    How does one separate game logic and rendering? I know there seem to already be questions on here asking exactly that but the answers are not satisfactory to me. From what I understand so far the point of separating them into different threads is so that game logic can start running for the next tick immediately instead of waiting for the next vsync where rendering finally returns from the swapbuffer call its been blocking on. But specifically what data structures are used to prevent race conditions between the game logic thread and the rendering thread. Presumably the rendering thread needs access to various variables to figure out what to draw, but game logic could be updating these same variables. Is there a de facto standard technique for handling this problem. Maybe like copy the data needed by the rendering thread after every execution of the game logic. Whatever the solution is will the overhead of synchronization or whatever be less than just running everything single threaded?

    Read the article

  • boost's regex won't compile

    - by myeviltacos
    Hi everyone. I am using boost 1.45.0 on Ubuntu with Code::Blocks as my IDE, and I can't get basic_regex.hpp to compile. I'm pretty sure I set up boost correctly, because I can compile programs using boost::format without any errors. But I'm getting this annoying error, and I don't know how to get rid of it. The code that is provoking the error: boost::regex e("\"http:\\\\/\\\\/localhostr.com\\\\/files\\\\/.+?\""); Compiler output (GCC): obj/Debug/main.o In function `boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::assign(char const*, char const*, unsigned int)' /home/neal/Documents/boost_1_45_0/boost/regex/v4/basic_regex.hpp|379| undefined reference to `boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::do_assign(char const*, char const*, unsigned int)'| ||=== Build finished: 1 errors, 0 warnings ===| Did I miss a step when setting up boost, or should I downgrade to another version of boost?

    Read the article

  • How to use/manipulate return value from nested boost::bind

    - by JQ
    I have two functions: 1. A & DataSource(); 2. void DataConsumer( A * ); What I want to achieve: Using one statement to assemble them into one functor. I have tried: 1. boost::function< void() func( boost::bind( DataConsumer, & boost::bind( DataSource ) ) ); certainly it didn't work, compiler says it can not convert 'boost::_bi::bind_t ' to 'A *' 2. boost::function< void() func( boost::bind( DataConsumer, boost::addressof( boost::bind( DataSource ) ) )); compiler says cannot convert parameter 1 from 'boost::_bi::bind_t' to 'A &' Question: how to use return value from the nested boost::bind ? or if you want to use boost::lambda::bind.

    Read the article

  • C# Thread Pool Cross-Thread Communication

    - by Goober
    The Scenario I have a windows forms application containing a MAINFORM with a listbox on it. The MAINFORM also has a THREAD POOL that creates new threads and fires them off to do lots of different bits of processing. Whilst each of these different worker threads is doing its job, I want to report this progress back to my MAINFORM, however, I can't because it requires Cross-Thread communication. Progress So far all of the tutorials etc. that I have seen relating to this topic involve custom(ish) threading implementations, whereas I literally have a fairly basic(ish) standard THREAD POOL implementation. Since I don't want to really modify any of my code (since the application runs like a beast with no quarms) - I'm after some advice as to how I can go about doing this cross-thread communication. ALTERNATIVELY - How to implement a different "LOGTOSCREEN" method altogether (obviously still bearing in mind the cross-thread communication thing). WARNING: I use this website at work, where we are locked down to IE6 only, and the javascript thus fails, meaning I cannot click accept on any answers during work, and thus my acceptance rate is low. I can't do anything about it I'm afraid, sorry. EDIT: I DO NOT HAVE INSTALL RIGHTS ON MY COMPUTER AT WORK. I do have firefox but the proxy at work fails when using this site on firefox. FURTHER EDIT: I DO NOT WANT TO CHANGE MY THREADING IMPLEMENTATION. AT ALL! - Accept to enable cross-thread communication....why would a backgroundworker help here!?

    Read the article

  • Boost::Asio : io_service.run() vs poll() or how do I integrate boost::asio in mainloop

    - by user300713
    Hi, I am currently trying to use boost::asio for some simple tcp networking for the first time, and I allready came across something I am not really sure how to deal with. As far as I understand io_service.run() method is basically a loop which runs until there is nothing more left to do, which means it will run until I release my little server object. Since I allready got some sort of mainloop set up, I would rather like tp update the networking loop manually from there just for the sake of simplicity, and I think io_service.poll() would do what I want, sort of like this: void myApplication::update() { myIoService.poll(); //do other stuff } This seems to work, but I am still wondering if there is a drawback from this method since that does not seem to be the common way to deal with boost::asios io services. Is this a valid approach or should I rather use io_service.run() in a non blocking extra thread?

    Read the article

  • Boost.Python wrapping hierarchies avoiding diamond inheritance

    - by stbuton
    I'm having some trouble seeing what the best way to wrap a series of classes with Boost.Python while avoiding messy inheritance problems. Say I have the classes A, B, and C with the following structure: struct A { virtual void foo(); virtual void bar(); virtual void baz(); }; struct B : public A { virtual void quux(); }; struct C : public A { virtual void foobar(); }; I want to wrap all classes A, B, and C such that they are extendable from Python. The normal method for accomplishing this would be along the lines of: struct A_Wrapper : public A, boost::python::wrapper<A> { //dispatch logic for virtual functions }; Now for classes B and C which extend from A I would like to be able to inherit and share the wrapping implementation for A. So I'd like to be able to do something along the lines of: struct B_Wrapper : public B, public A_Wrapper, public boost::python::wrapper<B> { //dispatch logic specific for B }; struct C_Wrapper : public C, public A_Wrapper, public boost::python::wrapper<C> { //dispatch logic specific for C } However, it seems like that would introduce all manner of nastiness with the double inheritance of the boost wrapper base and the double inheritance of A in the B_Wrapper and C_Wrapper objects. Is there a common way that this instance is solved that I'm missing? thanks.

    Read the article

  • Iterator for boost::variant

    - by Ivan
    Hy there, I'm trying to adapt an existing code to boost::variant. The idea is to use boost::variant for a heterogeneous vector. The problem is that the rest of the code use iterators to access the elements of the vector. Is there a way to use the boost::variant with iterators? I've tried typedef boost::variant<Foo, Bar> Variant; std::vector<Variant> bag; std::vector<Variant>::iterator it; for(it= bag.begin(); it != bag.end(); ++it){ cout<<(*it)<<endl; } But it didn't work.

    Read the article

  • Using boost::iterator

    - by Neil G
    I wrote a sparse vector class (see #1, #2.) I would like to provide two kinds of iterators: The first set, the regular iterators, can point any element, whether set or unset. If they are read from, they return either the set value or value_type(), if they are written to, they create the element and return the lvalue reference. Thus, they are: Random Access Traversal Iterator and Readable and Writable Iterator The second set, the sparse iterators, iterate over only the set elements. Since they don't need to lazily create elements that are written to, they are: Random Access Traversal Iterator and Readable and Writable and Lvalue Iterator I also need const versions of both, which are not writable. I can fill in the blanks, but not sure how to use boost::iterator_adaptor to start out. Here's what I have so far: template<typename T> class sparse_vector { public: typedef size_t size_type; typedef T value_type; private: typedef T& true_reference; typedef const T* const_pointer; typedef sparse_vector<T> self_type; struct ElementType { ElementType(size_type i, T const& t): index(i), value(t) {} ElementType(size_type i, T&& t): index(i), value(t) {} ElementType(size_type i): index(i) {} ElementType(ElementType const&) = default; size_type index; value_type value; }; typedef vector<ElementType> array_type; public: typedef T* pointer; typedef T& reference; typedef const T& const_reference; private: size_type size_; mutable typename array_type::size_type sorted_filled_; mutable array_type data_; // lots of code for various algorithms... public: class sparse_iterator : public boost::iterator_adaptor< sparse_iterator // Derived , array_type::iterator // Base (the internal array) (this paramater does not compile! -- says expected a type, got 'std::vector::iterator'???) , boost::use_default // Value , boost::random_access_traversal_tag? // CategoryOrTraversal > class iterator_proxy { ??? }; class iterator : public boost::iterator_facade< iterator // Derived , ????? // Base , ????? // Value , boost::?????? // CategoryOrTraversal > { }; };

    Read the article

  • buffer overflow with boost::program_options

    - by f4
    Hello, I have a problem using boost:program_options this simple program, copy-pasted from boosts' documentation : #include <boost/program_options.hpp> int main( int argc, char** argv ) { namespace po = boost::program_options; po::options_description desc("Allowed options"); desc.add_options() ("help", "produce help message") ("compression", po::value<int>(), "set compression level") ; return 0; } fails with a buffer overflow. I have activated the "buffer security switch", and when I run it I get an "unknown exception (0xc0000409)" when I step over the line desc.add_options()... I use Visual Studio 2005 and boost 1.43.0. By the way it does run if I deactivate the switch but I don't feel comfortable doing so... unless it's possible to deactivate it locally. So do you have a solution to this problem? EDIT I found the problem I was linking against libboost_program_options-vc80-mt.lib which wasn't the good library.

    Read the article

  • C++ boost thread id and Singleton

    - by aaa
    hi. Sorry to flood so many questions this week. I assume thread index returned by thread.get_id is implementation specific. In case of the pthreads, is index reused? IE, if thread 0 runs and joins, is thread launched afterwords going to have a different ID? the reason I ask this is a need to implement Singleton pattern with a twist: each thread gets its own instance. I know it sounds very crazy, but threads control hardware (cuda) which does not permit device memory sharing. What is a good way to implement such pattern?

    Read the article

  • Scalability of Boost.Asio

    - by samm
    I'm curious how far others have pushed Boost.Asio in terms of scalability. I am writing an application that may use close to 1000 socket objects, a handful of acceptor objects, and many thousand timer objects. I've configured it such that there's a thread pool invoking io_service::run and use strands in the appropriate places to ensure my handlers do not stomp on each other. My platform is Red Hat Enterprise Linux with Boost 1.39, though I'm not opposed to upgrading to a more recent version of boost.

    Read the article

  • Is boost shared_ptr <XXX> thread safe?

    - by sxingfeng
    I have a question about boost :: shared_ptr. There are lots of thread. class CResource { xxxxxx } class CResourceBase { public: void SetResource(shared_ptr<CResource> res) { m_Res = res; } shared_ptr<CResource> GetResource() { return m_Res; } private: shared_ptr<CResource> m_Res; } CResourceBase base; //---------------------------------------------- Thread A: while (true) { ...... shared_ptr<CResource> nowResource = base.GetResource(); nowResource.doSomeThing(); ... } Thread B: shared_ptr<CResource> nowResource; base.SetResource(nowResource); ... //----------------------------------------------------------- If thread A do not care the nowResource is the newest . Will this part of code have problem? I mean when ThreadB do not SetResource completely, Thread A get a wrong smart point by GetResource? Another question : what does thread-safe mean? If I do not care about whether the resource is newest, will the shared_ptr nowResource crash the program when the nowResource is released or will the problem destroy the shared_point?

    Read the article

  • WCF Service worker thread communicate with ServiceHost thread

    - by Brent
    I have a windows NT Service that opens a ServiceHost object. The service host context is per-session so for each client a new worker thread is created. What I am trying to do is have each worker thread make calls to the thread that started the service host. The NT Service needs to open a VPN connection and poll information from a device on the remote network. The information is stored in a SQL database for the worker threads to read. I only want to poll the device if there is a client connected, which will reduce network trafic. I would like the worker threads to tell the service host thread that they are requesting information and start the polling and updating the database. Everything is working if the device is alway being polled and the database being updated.

    Read the article

  • Using boost locks for RAII access to a semaphore

    - by dan
    Suppose I write a C++ semaphore class with an interface that models the boost Lockable concept (i.e. lock(); unlock(); try_lock(); etc.). Is it safe/recommended to use boost locks for RAII access to such an object? In other words, do boost locks (and/or other related parts of the boost thread library) assume that the Lockable concept will only be modeled by mutex-like objects which are locked and unlocked from the same thread? My guess is that it should be OK to use a semaphore as a model for Lockable. I've browsed through some of the boost source and it "seems" OK. The locks don't appear to store explicit references to this_thread or anything like that. Moreover, the Lockable concept doesn't have any function like whichThreadOwnsMe(). It also looks like I should even be able to pass a boost::unique_lock<MySemaphore> reference to boost::condition_variable_any::wait. However, the documentation is not explicitly clear about the requirements. To illustrate what I mean, consider a bare-bones binary semaphore class along these lines: class MySemaphore{ bool locked; boost::mutex mx; boost::condition_variable cv; public: void lock(){ boost::unique_lock<boost::mutex> lck(mx); while(locked) cv.wait(lck); locked=true; } void unlock(){ { boost::lock_guard<boost::mutex> lck(mx); if(!locked) error(); locked=false; } cv.notify_one(); } // bool try_lock(); void error(); etc. } Now suppose that somewhere, either on an object or globally, I have MySemaphore sem; I want to lock and unlock it using RAII. Also I want to be able to "pass" ownership of the lock from one thread to another. For example, in one thread I execute void doTask() { boost::unique_lock<MySemaphore> lock(sem); doSomeWorkWithSharedObject(); signalToSecondThread(); waitForSignalAck(); lock.release(); } While another thread is executing something like { waitForSignalFromFirstThread(); ackSignal(); boost::unique_lock<MySemaphore>(sem,boost::adopt_lock_t()); doMoreWorkWithSameSharedObject(); } The reason I am doing this is that I don't want anyone else to be able to get the lock on sem in between the time that the first thread executes doSomeWorkWithSharedObject() and the time the second executes doMoreWorkWithSameSharedObject(). Basically, I'm splitting one task into two parts. And the reason I'm splitting the task up is because (1) I want the first part of the task to get started as soon as possible, (2) I want to guarantee that the first part is complete before doTask() returns, and (3) I want the second, more time-consuming part of the task to be completed by another thread, possibly chosen from a pool of slave threads that are waiting around to finish tasks that have been started by master threads. NOTE: I recently posted this same question (sort of) here http://stackoverflow.com/questions/2754884/unlocking-a-mutex-from-a-different-thread-c but I confused mutexes with semaphores, and so the question about using boost locks didn't really get addressed.

    Read the article

  • A Basic Thread

    - by Joe Mayo
    Most of the programs written are single-threaded, meaning that they run on the main execution thread. For various reasons such as performance, scalability, and/or responsiveness additional threads can be useful. .NET has extensive threading support, from the basic threads introduced in v1.0 to the Task Parallel Library (TPL) introduced in v4.0. To get started with threads, it's helpful to begin with the basics; starting a Thread. Why Do I Care? The scenario I'll use for needing to use a thread is writing to a file.  Sometimes, writing to a file takes a while and you don't want your user interface to lock up until the file write is done. In other words, you want the application to be responsive to the user. How Would I Go About It? The solution is to launch a new thread that performs the file write, allowing the main thread to return to the user right away.  Whenever the file writing thread completes, it will let the user know.  In the meantime, the user is free to interact with the program for other tasks. The following examples demonstrate how to do this. Show Me the Code? The code we'll use to work with threads is in the System.Threading namespace, so you'll need the following using directive at the top of the file: using System.Threading; When you run code on a thread, the code is specified via a method.  Here's the code that will execute on the thread: private static void WriteFile() { Thread.Sleep(1000); Console.WriteLine("File Written."); } The call to Thread.Sleep(1000) delays thread execution. The parameter is specified in milliseconds, and 1000 means that this will cause the program to sleep for approximately 1 second.  This method happens to be static, but that's just part of this example, which you'll see is launched from the static Main method.  A thread could be instance or static.  Notice that the method does not have parameters and does not have a return type. As you know, the way to refer to a method is via a delegate.  There is a delegate named ThreadStart in System.Threading that refers to a method without parameters or return type, shown below: ThreadStart fileWriterHandlerDelegate = new ThreadStart(WriteFile); I'll show you the whole program below, but the ThreadStart instance above goes in the Main method. The thread uses the ThreadStart instance, fileWriterHandlerDelegate, to specify the method to execute on the thread: Thread fileWriter = new Thread(fileWriterHandlerDelegate); As shown above, the argument type for the Thread constructor is the ThreadStart delegate type. The fileWriterHandlerDelegate argument is an instance of the ThreadStart delegate type. This creates an instance of a thread and what code will execute, but the new thread instance, fileWriter, isn't running yet. You have to explicitly start it, like this: fileWriter.Start(); Now, the code in the WriteFile method is executing on a separate thread. Meanwhile, the main thread that started the fileWriter thread continues on it's own.  You have two threads running at the same time. Okay, I'm Starting to Get Glassy Eyed. How Does it All Fit Together? The example below is the whole program, pulling all the previous bits together. It's followed by its output and an explanation. using System; using System.Threading; namespace BasicThread { class Program { static void Main() { ThreadStart fileWriterHandlerDelegate = new ThreadStart(WriteFile); Thread fileWriter = new Thread(fileWriterHandlerDelegate); Console.WriteLine("Starting FileWriter"); fileWriter.Start(); Console.WriteLine("Called FileWriter"); Console.ReadKey(); } private static void WriteFile() { Thread.Sleep(1000); Console.WriteLine("File Written"); } } } And here's the output: Starting FileWriter Called FileWriter File Written So, Why are the Printouts Backwards? The output above corresponds to Console.Writeline statements in the program, with the second and third seemingly reversed. In a single-threaded program, "File Written" would print before "Called FileWriter". However, this is a multi-threaded (2 or more threads) program.  In multi-threading, you can't make any assumptions about when a given thread will run.  In this case, I added the Sleep statement to the WriteFile method to greatly increase the chances that the message from the main thread will print first. Without the Thread.Sleep, you could run this on a system with multiple cores and/or multiple processors and potentially get different results each time. Interesting Tangent but What Should I Get Out of All This? Going back to the main point, launching the WriteFile method on a separate thread made the program more responsive.  The file writing logic ran for a while, but the main thread returned to the user, as demonstrated by the print out of "Called FileWriter".  When the file write finished, it let the user know via another print statement. This was a very efficient use of CPU resources that made for a more pleasant user experience. Joe

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >