I have a thread which I am creating whenever an object is created of the class , the thread I am creating in the constructor itself. So, depending on how many objects are created , the number of threads will be equal to number of objects created. But I want to create only a single thread , no matter how many objects are created..
Any help would be appreciated.
I can't put the code here as it is too big. A simple suggestion will be helpful for me.
You can use singleton design pattern to restrict an object to have one (or specific number of) instance(s). Moreover, look at this for a thread safe implementation if you create object from multiple threads.
I would suggest to move thread into separate class and make its static object in your main class te something like this
MyThreadClass {
// implement your code to handle thread
};
MyObjectClass {
static MyThreadClass* myThread; // static object to keep single thread
};
main() {
// create multiple MyObjectClass
}
I made very simple code to check this concept with std::thread
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.