码迷,mamicode.com
首页 > 编程语言 > 详细

c++多线程实例

时间:2015-04-15 23:09:39      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

#include <windows.h>
#include <stdio.h>
#include <process.h>

int g_ntotal = 100;
int g_thread_counter;
int g_sum;//计算结果
HANDLE g_thread_lock;//HANDLE 被类型定义为 void *

struct THREAD_DATA
{
    int num_threads;
    int thread_id;
};

void sum_func(void *pdata)
{
    THREAD_DATA *ptdata = (THREAD_DATA *)pdata;

    int i, sum = 0;
    for (i = ptdata->thread_id; i <= g_ntotal; i += ptdata->num_threads)
        sum += i;

    delete ptdata;

    WaitForSingleObject(g_thread_lock, INFINITE);
    g_sum += sum;
    --g_thread_counter;
    ReleaseMutex(g_thread_lock);
}

void main(void)
{
    LARGE_INTEGER hfreq, hcounter1, hcounter2;//这三个货是64位的整数
    QueryPerformanceFrequency(&hfreq);
    //printf("%ld",hfreq);
    SYSTEM_INFO sys_info;//这货是结构体变量
    GetSystemInfo(&sys_info);//实参为指向结构体的指针
    int num_processors = sys_info.dwNumberOfProcessors;//值为2,是一个DWORD类型的成员变量,DWORD被定义为无符号长整型
    //num_processors = 1;
    
    printf("Number of processors=%d\n", num_processors);//机器支持的线程数目

    g_thread_lock = CreateMutex(NULL, FALSE, NULL);//返回值为无类型指针,CreateMutex作用是找出当前系统是否已经存在指定进程的实例。如果没有则创建一个互斥体。

    g_thread_counter = num_processors;//系统支持的线程数
    g_sum = 0;//计算结果初始化

    QueryPerformanceCounter(&hcounter1);//获取当前时间保存到 hcounter1 中,实参是指向64位整数的指针

    int i;
    THREAD_DATA *pdata;//THREAD_DATA是本程序中自己定义的结构体
    for (i = 1; i < num_processors; ++i)
    {
        pdata = new THREAD_DATA;
        pdata->thread_id = i + 1;
        pdata->num_threads = num_processors;//值为2
        _beginthread(sum_func, 0, pdata);
    }

    pdata = new THREAD_DATA;
    pdata->thread_id = 1;
    pdata->num_threads = num_processors;//值为2
    sum_func(pdata);

    while (1)
    {
        int itemp;
        WaitForSingleObject(g_thread_lock, INFINITE);
        itemp = g_thread_counter;//系统支持的线程数,值为2
        ReleaseMutex(g_thread_lock);
        if (itemp == 0) break;
    }

    QueryPerformanceCounter(&hcounter2);//获取结束时间,保存到 hcounter2 中

    double dt = (double)(hcounter2.QuadPart - hcounter1.QuadPart)
        / (double)hfreq.QuadPart;//表达式中涉及的三个变量是共用体类型(8字节),其中QuadPart是共用体的 long long类型成员,在此处被毫无节操地转换成了double类型,double也是占用8字节

    printf("sum=%d\n", g_sum);
    printf("Calculation time=%f\n", dt);//此处将%g改为了%f,这里是代码的运行时间
    //printf("%d", sizeof(double));
    getchar();

    CloseHandle(g_thread_lock); //将CreateMutex创建的互斥体关闭
}

 

c++多线程实例

标签:

原文地址:http://www.cnblogs.com/zhanghaha/p/4430288.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!