线程学习一 _beginthread

重点内容
reinterpret_cast <>() 两个不相干的类型转换 <类型>(变量名)

重要看msdn 关于函数的解释

无参数线程函数

void Fun()
{

    for (int i = 0; i < 100; i++)
    {
        printf("%d\r\n", i);

    }
}
int _tmain(int argc, _TCHAR* argv[])
{
    uintptr_t handle=_beginthread((void(__cdecl *)(void *))Fun, NULL, NULL);
    WaitForSingleObject(reinterpret_cast<HANDLE>(handle), INFINITE);
    CloseHandle(reinterpret_cast<HANDLE>(handle));
    return 0;
}

带参数的线程函数
很简单效果一样 1-100 遍历

void Fun(int num)
{

    for (int i = 0; i < num; i++)
    {
        printf("%d\r\n", i);

    }
}
int _tmain(int argc, _TCHAR* argv[])
{

    int num = 100;
    uintptr_t handle=_beginthread((void(__cdecl *)(void *))Fun, NULL, (void*)num);
    WaitForSingleObject(reinterpret_cast<HANDLE>(handle), INFINITE);
    CloseHandle(reinterpret_cast<HANDLE>(handle));
    return 0;
}

线程的控制

遍历到50
这个例子其实不是多好 ,自己可以试试,写个界面进行控制。

// 线程学习1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>
#include <process.h>
bool isExit = false;
void Fun(int num)
{
    if (!isExit)
    {

        for (int i = 0; i < num; i++)
        {
            printf("%d\r\n", i);
            if (i == 50)
            {
                isExit = true;
                break;
            }
        }
    }

}
int _tmain(int argc, _TCHAR* argv[])
{

    int num = 100;

    uintptr_t handle = _beginthread((void(__cdecl *)(void *))Fun, NULL, (void*)num);
    WaitForSingleObject(reinterpret_cast<HANDLE>(handle), INFINITE);
    CloseHandle(reinterpret_cast<HANDLE>(handle));


    return 0;
}

多线程
这里写图片描述
出现数据问题 解决办法有很多。
例如把sleep 时间加长 相当于4个人同时赛跑 有的人跑的快 有的跑的慢
其实这样修改不是多好,感觉不灵活。可以进行考虑加锁临界区,信号量,互斥体,原子锁等
后面有时间我写下,复习下。

线程同步问题

// 线程学习1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <windows.h>
#include <process.h>
bool isExit = false;
void Fun(int num)
{

        for (int i = 0; i < num; i++)
        {
            printf("%d\r\n", i);

        }

}
int _tmain(int argc, _TCHAR* argv[])
{

    int num = 100;
    uintptr_t handle[4];
    for (int i=0; i < 4;i++)
    {
        handle[i]= _beginthread((void(__cdecl *)(void *))Fun, NULL, (void*)num);
        Sleep(10);
    }

    return 0;
}

解决代码大家自己动手

猜你喜欢

转载自blog.csdn.net/h1028962069/article/details/78004418