多线程实例代码 - 面向过程语言

#include <iostream>   
#include <windows.h>   
using namespace std;

DWORD WINAPI Fun(LPVOID lpParamter)
 {
     for (int i = 0; i < 10; i++)
         cout << "A Thread Fun Display!" << endl;
     return 0L;
 }
 
int main()
 {
     HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
     CloseHandle(hThread);
     for (int i = 0; i < 10; i++)
         cout << "Main Thread Display!" << endl;
     return 0;
 }

#include <iostream>   
#include <windows.h>   
using namespace std;

DWORD WINAPI Fun(LPVOID lpParamter)
{
    for (int i = 0; i < 10; i++)
    {
        cout << "A Thread Fun Display!" << endl;
        Sleep(200);
    }
        
    return 0L;
}

int main()
{
    HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
    CloseHandle(hThread);
    for (int i = 0; i < 10; i++)
    {
        cout << "Main Thread Display!" << endl;
        Sleep(500);
    }
        
    return 0;
}


#include <iostream>   
#include <windows.h>   
using namespace std;

DWORD WINAPI Fun(LPVOID lpParamter)
{
    for (int i = 0; i < 10; i++)
    {
        //cout << "A Thread Fun Display!" << endl;
        cout << "A Thread Fun Display!\n";
        Sleep(200);
    }
        
    return 0L;
}

int main()
{
    HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
    CloseHandle(hThread);
    for (int i = 0; i < 10; i++)
    {
        //cout << "Main Thread Display!" << endl;
        cout << "Main Thread Display!\n";
        Sleep(500);
    }
        
    return 0;
}


#include <iostream>
#include <windows.h>
using namespace std;

HANDLE hMutex = NULL;//互斥量
//线程函数
DWORD WINAPI Fun(LPVOID lpParamter)
{
    for (int i = 0; i < 10; i++)
    {
        //请求一个互斥量锁
        WaitForSingleObject(hMutex, INFINITE);
        cout << "A Thread Fun Display!" << endl;
        Sleep(100);
        //释放互斥量锁
        ReleaseMutex(hMutex);
    }
    return 0L;//表示返回的是long型的0

}

int main()
{
    //创建一个子线程
    HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
    hMutex = CreateMutex(NULL, FALSE,"screen");
    //关闭线程
    CloseHandle(hThread);
    //主线程的执行路径
    for (int i = 0; i < 10; i++)
    {
        //请求获得一个互斥量锁
        WaitForSingleObject(hMutex,INFINITE);
        cout << "Main Thread Display!" << endl;
        Sleep(100);
        //释放互斥量锁
        ReleaseMutex(hMutex);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值