C ++ 동시 프로그래밍의 기초

C ++에서의 쓰레드 라이브러리 native_handle()플랫폼 별 API를 사용하여 멤버 함수가 기본이되는 구현의 직접 조작 할 수 있습니다.

동시에 기능을 실행하기 위해 여러 스레드를 관리하는 특정 기능 및 객체의 사용을 필요로한다. C ++ 헤더 파일 그것은 클래스와 함수 관리 스레드를 제공합니다

헬로 간단한, 동시 World 프로그램 :

#include <iostream>
#include <thread>  //①
void hello()  //②
{
  std::cout << "Hello Concurrent World\n";
}
int main()
{
  std::thread t(hello);  //③
  t.join();  //④
}

어느 방법을 호출 std::thread여전히 볼 STD 도메인이며, 동시에 join기능을 보장하기 위하여 인 t의 완료 후에 실행 스레드가 main종료 될 때까지 메인 쓰레드.

스레드를 시작합니다

스레드는 스레드 객체가 생성 될 때, 즉 건설 스레드가 시작 std::thread개체를 시작합니다. 그것은 우리가 스레드 사이에만 상호 제어를 달성 할 수있는 공유 변수를 설정해야 할 말을하는 것입니다.

  • 방법 세 가지 구조 :
std::thread my_thread(background_task);     // 1
std::thread my_thread((background_task())); // 2
std::thread my_thread{background_task()};   // 3
  • 스레드를 시작한 후, 나사 끝을 기다리는 명확한 필요 (스타일을 결합), 또는 자율적으로 실행 (별도) 할 수있다
t.detach(); //(分离式),new和current线程无关
t.join();   //(加入式),阻塞current线程,执行新线程
  • 스레드 간의 변수가 필요합니다 수정하여 std::ref()참조 데이터로 데이터를 변환 :
std::thread t(update_data_for_widget,w,std::ref(data));

데이터 보안의 동기화

std::mutex mt;
void addmethod(int a)
{
    mt.lock();
    addprocessing(...);
    mt.unlock();
}
void deletemethod(int a)
{
    mt.lock();
    deleteprocessing(...);
    mt.unlock();
}

unique_lock 사용하거나 lock_guard 잠겨 얻을 수 있습니다.

std::mutex mt;
void addmethod(int a)
{
    std::unique_lock<std::mutex> lock(mt);
    addprocessing(...);
}
void deletemethod(int a)
{
    std::unique_lock<std::mutex> l(mt);
    deleteprocessing(...);
}

추천

출처www.cnblogs.com/FlameBlog/p/10939590.html