ข้ามไปที่เนื้อหาหลัก

Thread บน C++0x

หลังจากนั่งเขียนโค้ดมาหลายวัน วันนี้จะต้องเขียนบางส่วนที่ทำงานโดยใช้เธรด (thread) จึงลองเขียนเล่นๆ นอกโปรเจคก่อน ผลออกมาน่าพอใจทีเดียว แต่ตอนคอมไพล์โปรแกรมต้องเพิ่มออพชันเข้าไปเพื่อให้ g++ รู้ว่ามีการใช้งานมาตรฐาน C++0x และเพิ่ม pthread เข้าไปด้วยมิฉะนั้นจะรันไม่ผ่าน ตัวอย่างโค้ดชื่อ thread.cpp
#include <iostream>
#include <thread>
using namespace std;

class DoWork
{
public:
   void operator()(int a, int b){
       cout << "hello in thread a is " << a << " b is " << b << endl;
   }
};

void hello_thread(){
   cout << "hello from function" << endl;
}

int main(){
DoWork dw;
thread a(dw, 10, 20);

thread b(hello_thread);

a.join();
b.join();

return 0;
}


หลังจากนั้นทดสอบคอมไพล์โปรแกรมแบบไม่เพิ่มไลบรารี pthread ดู จะแสดงข้อผิดพลาดดังด้านล่าง
$ g++ --std=c++0x -o thread thread.cpp 
$ ./thread 
terminate called after throwing an instance of 'std::system_error'
  what():  Operation not permitted
Aborted

หากเพิ่มไลบรารี pthread ก็สามารถรันได้
$ g++ --std=c++0x -lpthread -o thread thread.cpp 
$ ./thread 
hello from function
hello in thread a is 10 b is 20

หลังจากทดสอบดูเป็นที่น่าพอใจไม่ต้องเขียน pthread เองให้ยุ่งยาก มี mutex ให้ใช้ด้วยแต่ยังไม่ทดสอบเขียนดูครับ

ความคิดเห็น