2021/03 自我面试之多线程

一、多线程

1.如何创建多线程

两种方式:

(1)使用头文件<pthread.h>

#include <pthread.h>
#include <iostream>

#define THREAD_NUM 5

void say_hello(void *args)
{
    std::cout << "hello, wangshuo" << std::endl;
    return 0;
}

int main()
{
    pthread_t tid[THREAD_NUM];
    
    for(int i = 0; i < THREAD_NUM; ++i)
    {
        int ret = pthread_create(&tid[i], NULL, say_hello, NULL);
        if(ret != 0)
            std::cout << "thread error" << std::endl;
        
    }

}

(2)使用C++11新特性,头文件 <thread>

#include <iostream>
#include <thread>
#include <vector>

#define THREAD_NUM 5

void* say_hello(int n)
{
    std::cout << "hello, wangshuo" << std::endl;
    return 0;
}

int main()
{

    std::thread thread1(say_hello, 3);
    if(thread1.joinable());
        thread1.join();
    
    //创建多个线程,可以使用vector
    std::vector<std::thread> v_thread;
    for(int i = 0; i < THREAD_NUM; ++i)
    {
        v_thread.push_back(std::thread(say_hello, i));

    }
    
    for(auto iter = v_thread.begin(); iter != v_thread.end(); ++iter)
    {
        iter -> join(); 
    }


}

2.线程同步和互斥的方式有哪些?如何实现?

线程同步的方式有:用户模式:原子操作和临界区,内核模式:互斥、信号量和事件

(1)原子操作(atomic)

参考链接:https://blog.csdn.net/m0_37621078/article/details/89980205

#include <iostream>
#include <atomic>
#include <thread>
#include <chrono>

std::chrono::millisecond interval(100);

std::atomic<bool> readyFlag(false);
std::atomic<int> job_shared(0);
int job_exclusive = 0;

void job_1()
{
    std::this_thread::sleep_for(5 * interval);
    job_shared.fetch_add(1);
    std::cout << "job_1 shared: " << job_shared.load() << std::endl;
    readyFlag.store(true);

}

void job_2()
{
     while (true) {    //无限循环,直到可访问并修改'job_shared'
        if (readyFlag.load()) {     //判断布尔标记状态是否为真,为真则修改‘job_shared’
            job_shared.fetch_add(1);
            std::cout << "job_2 shared (" << job_shared.load() << ")\n";
            return;
        } else {      //布尔标记为假,则修改'job_exclusive'
            ++job_exclusive;
            std::cout << "job_2 exclusive (" << job_exclusive << ")\n";
            std::this_thread::sleep_for(interval);
        }
    }

}

int main()
{

    std::thread thread_1(job_1);
    std::thread thread_2(job_2);

    thread_1.join();
    thread_2.join();

    getchar()
    return 0;

}

(2)临界区

参考链接:https://blog.csdn.net/shihz_fy/article/details/52435074

#include <windows.h>
#include <iostream>
#include <thread>

using namespace std;

struct MyStruct
{
    int a;
    int b;
};
MyStruct s;

CRITICAL_SECTION cs;
void funcPrint(){

    int count = 0;
    while (count < 20){
        count++;
        EnterCriticalSection(&cs);
        cout << s.a << " " << s.b << endl;
        LeaveCriticalSection(&cs);
        Sleep(1000);
    }
}

void funAdd(){
    int count = 0;
    while (count < 20){
        count++;
        EnterCriticalSection(&cs);
        s.a++;
        Sleep(400);
        s.b++;
        LeaveCriticalSection(&cs);
        Sleep(500);
    }

}

int main()
{
    s.a = 0;
    s.b = 0;
    InitializeCriticalSection(&cs);
    std::thread t(funcPrint);
    std::thread t2(funAdd);
    t.join();
    t2.join();
    return 0;
}

 

(3)信号量

参考链接:https://blog.csdn.net/u012967763/article/details/82843098

#include <iostream>
#include <Windows.h>

using namespace std;

static int number = 10;

HANDLE Sem;

DWORD WINAPI ThreadOne(LPVOID lpParameter)
{
    cout << "窗口1售票开始"<< endl;
    while (1)
    {
        WaitForSingleObject(Sem, INFINITE);
        if (number > 0)
        {
            cout << "窗口1售出第" << number << "张票" << endl;
            --number;
            Sleep(1000);
        }
        ReleaseSemaphore(Sem, 1, NULL);
    }
    return 0;
}

DWORD WINAPI ThreadTwo(LPVOID lpParameter)
{
    cout << "窗口2售票开始" << endl;
    while (1)
    {
        WaitForSingleObject(Sem, INFINITE);
        if (number > 0)
        {
            cout << "窗口2售出第" << number << "张票" << endl;
            --number;
            Sleep(1000);
        }
        ReleaseSemaphore(Sem, 1, NULL);
    }
    return 0;
}

int main()
{
    HANDLE HOne, HTwo;
    Sem = CreateSemaphore(NULL, 1, 1, NULL);//初始值为1,最大值为1
    HOne = CreateThread(NULL, 0, ThreadOne, NULL, 0, NULL);
    HTwo = CreateThread(NULL, 0, ThreadTwo, NULL, 0, NULL);
    CloseHandle(HOne);
    CloseHandle(HTwo);
    while (TRUE)
    {
        if (number == 0)
        {
            cout << "不好意思,票卖完了!" << endl;
            CloseHandle(Sem);
            return 0;
        }
        else
        {
            continue;
        }
    }
    system("Pause");
    return 0;
}

(4)事件

(5)互斥

锁的类型:互斥锁、条件锁、自旋锁、读写锁、递归锁

(6)死锁产生的原因以及如何解除死锁问题

参考链接:https://blog.csdn.net/weixin_38416696/article/details/90598963

https://www.jianshu.com/p/c01e992a3d9d?utm_campaign=maleskine

https://www.jb51.net/article/134033.htm

http://c.zhizuobiao.com/c-18060400024/

http://c.biancheng.net/view/1236.html

二、进程通信方式

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值