কম্পিউটার

আমি কিভাবে C++ 11 এ একটি থ্রেড শেষ করব?


এখানে আমরা দেখব, কিভাবে C++11-এ থ্রেডগুলিকে শেষ করা যায়। থ্রেডগুলি বন্ধ করার জন্য C++11-এর সরাসরি পদ্ধতি নেই।

std::future থ্রেডে ব্যবহার করা যেতে পারে এবং ভবিষ্যতে মান উপলব্ধ হলে এটি প্রস্থান করা উচিত। যদি আমরা থ্রেডে একটি সংকেত পাঠাতে চাই, কিন্তু প্রকৃত মান না পাঠাই, তাহলে আমরা অকার্যকর টাইপ অবজেক্ট পাস করতে পারি।

একটি প্রতিশ্রুতি বস্তু তৈরি করতে, আমাদের এই সিনট্যাক্স অনুসরণ করতে হবে −

std::promise<void> exitSignal;

এখন মূল ফাংশনে এই তৈরি প্রতিশ্রুতি বস্তু থেকে সংশ্লিষ্ট ভবিষ্যত অবজেক্ট আনুন -

std::future<void> futureObj = exitSignal.get_future();

এখন থ্রেড তৈরি করার সময় প্রধান ফাংশনটি পাস করুন, ভবিষ্যতের বস্তুটি পাস করুন −

std::thread th(&threadFunction, std::move(futureObj));

উদাহরণ

#include <thread>
#include <iostream>
#include <assert.h>
#include <chrono>
#include <future>
using namespace std;
void threadFunction(std::future<void> future){
   std::cout << "Starting the thread" << std::endl;
   while (future.wait_for(std::chrono::milliseconds(1)) == std::future_status::timeout){
      std::cout << "Executing the thread....." << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(500)); //wait for 500 milliseconds
   }
   std::cout << "Thread Terminated" << std::endl;
}
main(){
   std::promise<void> signal_exit; //create promise object
   std::future<void> future = signal_exit.get_future();//create future objects
   std::thread my_thread(&threadFunction, std::move(future)); //start thread, and move future
   std::this_thread::sleep_for(std::chrono::seconds(7)); //wait for 7 seconds
   std::cout << "Threads will be stopped soon...." << std::endl;
   signal_exit.set_value(); //set value into promise
   my_thread.join(); //join the thread with the main thread
   std::cout << "Doing task in main function" << std::endl;
}

আউটপুট

Starting the thread
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Threads will be stopped soon....
Thread Terminated
Doing task in main function

  1. অ্যান্ড্রয়েডে বর্তমান থ্রেড আইডি কীভাবে পাবেন?

  2. অ্যান্ড্রয়েডে thread.sleep() কীভাবে ব্যবহার করবেন?

  3. কীভাবে অ্যান্ড্রয়েডে একটি থ্রেড তৈরি করবেন?

  4. Tkinter Python এ থ্রেড কিভাবে ব্যবহার করবেন?