LoginSignup
1
3

More than 5 years have passed since last update.

C++におけるスレッド処理の実装

Last updated at Posted at 2018-07-31

ノーマルのスレッド処理

header.h
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>

class Test{
    public:
        static void ThreadProcess1();
        static void ThreadProcess2();
        void MainFunction();
};
main.cpp
include "header.h"

std::mutex mtx;

void Test::ThreadProcess1(){
    mtx.lock();    /*メモリの占有*/
    /*各スレッドで共有する関数や変数の処理はここに書く*/
    mtx.unlock();  /*解放*/
}
void Test::ThreadProcess2(){
    mtx.lock();    /*メモリの占有*/
    /*各スレッドで共有する関数や変数の処理はここに書く*/
    mtx.unlock();  /*解放*/
}

void Test::MainFunction(){
    std::thread th1(ThreadProcess1);
    std::thread th2(ThreadProcess2);
    th1.join();
    th2.join();
}

int main(int argc, char **argv){
    Test tc;
    tc.MainFunction();
    return 0;
}

各スレッドのプライオリティの設定

header.h
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <pthread.h>

class Test{
    public:
        static void ThreadProcess1();
        static void ThreadProcess2();
        void MainFunction();
};
main.cpp
include "header.h"

std::mutex mtx;

void Test::ThreadProcess1(){
    mtx.lock();    /*メモリの占有*/
    /*各スレッドで共有する関数や変数の処理はここに書く*/
    mtx.unlock();  /*解放*/

    sched_param sch;
    int policy;
    pthread_getschedparam(pthread_self(), &policy, &sch);
    std::cout << "Thread_Priority(Process1): "<< sch.sched_priority << std::endl;
}
void Test::ThreadProcess2(){
    mtx.lock();    /*メモリの占有*/
    /*各スレッドで共有する関数や変数の処理はここに書く*/
    mtx.unlock();  /*解放*/

    sched_param sch;
    int policy;
    pthread_getschedparam(pthread_self(), &policy, &sch);
    std::cout << "Thread_Priority(Process2): " << sch.sched_priority << std::endl;

}

void Test::MainFunction(){
    sched_param sch;
    sch.sched_priority = 1;
    std::thread th1(ThreadProcess1);
    std::thread th2(ThreadProcess2);
    pthread_setschedparam(th1.native_handle(), SCHED_FIFO, &sch));
    th1.join();
    th2.join();
}

int main(int argc, char **argv){
    Test tc;
    tc.MainFunction();
    return 0;
}

Thread_Priority(Process1): 1
Thread_Priority(Process2): 0

いろいろいらないものがあるハズ。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3