Vous êtes sur la page 1sur 9

3IS – Programmation parallèle

-
Threads C++11

2016 – David Picard

picard@ensea.fr

ÉCOLE NATIONALE SUPÉRIEURE DE L'ÉLECTRONIQUE ET DE SES APPLICATIONS


class std::thread
● #include <thread>
● Constructeur avec la fonction à exécuter dans
le thread :
void func(int, char) { … }

thread th(func, 3, 'b');

● Attente de fin avec join():


th.join();

ÉCOLE NATIONALE SUPÉRIEURE DE L'ÉLECTRONIQUE ET DE SES APPLICATIONS


class std::thread
● Fonctionne avec un callable:
class task {
void operator()() {
cout << “called” << endl;
}
};

task t;
thread th(t);

● fonctionne avec des lambdas:


thread th([]{ cout << “lambda” << endl;});

ÉCOLE NATIONALE SUPÉRIEURE DE L'ÉLECTRONIQUE ET DE SES APPLICATIONS


class std::mutex
● lock, try_lock, unlock
mutex m;
m.lock();
m.try_lock();
m.unlock();

● Protection d'une méthode:


class truc {
mutex m;

void func() {
m.lock();

// code

m.unlock();
};

ÉCOLE NATIONALE SUPÉRIEURE DE L'ÉLECTRONIQUE ET DE SES APPLICATIONS


unique_lock
● Objet temporaire pour section critique
mutex m;
unique_lock<mutex> lck(m);

● Protection d'une méthode:


class truc {
mutex m;

void func() {
unique_lock<mutex> lck(m);

// code

// unlock automatique à destruction de lck


};

ÉCOLE NATIONALE SUPÉRIEURE DE L'ÉLECTRONIQUE ET DE SES APPLICATIONS


atomic
● rendre une ressource critique
atomic<int> acc(0);
acc += 12;

● fonctionne avec un nombre limité de type


std::atomic_char std::atomic<char>
std::atomic_schar std::atomic<signed char>
std::atomic_uchar std::atomic<unsigned char>
std::atomic_short std::atomic<short>
std::atomic_ushort std::atomic<unsigned short>
std::atomic_int std::atomic<int>
std::atomic_uint std::atomic<unsigned int>
std::atomic_long std::atomic<long>
...

ÉCOLE NATIONALE SUPÉRIEURE DE L'ÉLECTRONIQUE ET DE SES APPLICATIONS


async et future
● Exécuter du code de manière asynchrone
async(isprime, 133223);
// async (callable, args...)

● Valeur de retour dans un future


future<bool> async(isprime, 133223);
// nouveau thread créé, calcul en parallèle

bool b = f.get(); // appel bloquant jusqu'à


// terminaison du thread

ÉCOLE NATIONALE SUPÉRIEURE DE L'ÉLECTRONIQUE ET DE SES APPLICATIONS


variable condition
● attente
mutex m;
condition_variable cv;

void func() {
unique_lock<mutex> lck(m);
cv.wait(lck);

● signalement
cv.notify_one(); // libère 1 thread

cv.notify_all(); // libère tous les threads


// attention, 1 seul mutex locké à la
// fois

● condition ad hoc
cv.wait(lck, []{ return ok==1;});
// équivalent à
while(ok != 1) cv.wait(lck);

ÉCOLE NATIONALE SUPÉRIEURE DE L'ÉLECTRONIQUE ET DE SES APPLICATIONS


thread pool
● À faire soit même...
class thread_pool {
vector<worker*> worker;
queue<task*> tasks;

execute(task* t);
...

● worker
● abstraction d'un thread
● tourne en permanence pour vider la queue de task
● Task
● abstraction d'une tâche (callable)

ÉCOLE NATIONALE SUPÉRIEURE DE L'ÉLECTRONIQUE ET DE SES APPLICATIONS

Vous aimerez peut-être aussi