zoukankan      html  css  js  c++  java
  • windows 和 linux 多线程

      学习了几天多线程技术,做个总结,便于记忆。

      一般 多线程传递参数 为 void*  所以会有一个强制转换过程  (int*) (void *)等,传递多个参数选择 结构体指针。为了避免多个线程访问数据冲突 会有一个 叫做  “临界区”CRITICALSECTION“ 类 ,防止读写数据冲突,

    大概流程是:

    CRITICAL_SECTION cs;

    init CS(cs);

    the one process

    enter CS

    .....

    leaveCS

    DELETE(cs);

    在利用多线程时候,会遇到数据分割的问题 一般的规定是:

    假设 data = N   process_num = M;

    N 能整除M 简单  N/M

    N 不能整除 M  则 M-1 个进程的数据处理数 为 N/(M-1) 最后一个进程处理数为N - (N/(M-1)*(M-1))

    一般利用全局变量完成线程间的简单通信 。当然也有timer定时器控制线程启动 ,和event事件触发线程。

    WINDOWS下 多线程头文件为 process.h

    LINUX下     。。。               pthread.h 另外编译时候 加上 -lpthread

    WINDOWS 新建一个线程 有 CreateThread _beginthread (略过参数)

    LINUX下    。。。            pthread_create

    WINDOWS 冻结解冻线程为 SuspendThread() ResumeThread()

    LINUX下 。。。一般用线程锁  pthread_mutex_lock   pthread_mutex_unlock

    /*程序流程为:主线程创建子线程(当前子线程状态为stop停止状态),5秒后主线程唤醒子线程,10秒后主线程挂起子线程,15秒后主线程再次唤醒子线程,20秒后主线程执行完毕等待子线程退出。
    
    代码如下:*/
    #include "stdio.h"
    #include "unistd.h"
    #include "pthread.h"
    #include "string.h"
    #include "time.h"
    
    #define RUN 1
    #define STOP 0
    
    pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
    
    int status = STOP;
    void * thread_function(void)
    {
        static int i = 0;
        while (1) 
        {   
            pthread_mutex_lock(&mut);
            while (!status)
            {
                pthread_cond_wait(&cond, &mut);
            }
            pthread_mutex_unlock(&mut);
        
            printf("child pthread %d
    ", i++);
            if (i == 20) 
                break;
            sleep(1);
        }   
    }
    
    void thread_resume()
    {
        if (status == STOP)
        {   
            pthread_mutex_lock(&mut);
            status = RUN;
            pthread_cond_signal(&cond);
            printf("pthread run!
    ");
            pthread_mutex_unlock(&mut);
        }   
        else
        {   
            printf("pthread run already
    ");
        }   
    }
    
    void thread_pause()
    {
        if (status == RUN)
        {   
            pthread_mutex_lock(&mut);
            status = STOP;
            printf("thread stop!
    ");
            pthread_mutex_unlock(&mut);
        }   
        else
        {   
            printf("pthread pause already
    ");
        }
    }
    
    int main()
    {
        int err;
        static int i = 0;
        pthread_t child_thread;
    
    #if 0
        if (pthread_mutex_init(&mut, NULL) != 0)
            printf("mutex init error
    ");
        if (pthread_cond_init(&cond, NULL) != 0)
            printf("cond init error
    ");
    #endif
    
        err = pthread_create(&child_thread, NULL, (void *)thread_function, NULL);
        if (err != 0 )
            printf("can't create thread: %s
    ", strerror(err));
        while(1)
        {
            printf("father pthread %d
    ", i++);
            sleep(1);
            if (i == 5)
                thread_resume();
            if (i == 10)
                thread_pause();
            if (i == 15)
                thread_resume();
            if (i == 20)
                break;
        }
        if (0 == pthread_join(child_thread, NULL))
            printf("child thread is over
    ");
        return 0;
    }

    。。。。。涉及到线程间的同步与异步一般会用到如下函数。。。。。。。。。。。。

    windows 等待线程结束  WaitForSingleObject() WaitForMultipleObjects()

    Linux 。。。   pthread_join()

    windows 退出线程 ExitThread() TerminateThread()/强制结束线程

    linux 退出线程  pthread_exit() 

    还有关键的 SIGNAL 没有学习,再UPDATE吧。

    最后附上linux 和windows 多线程测试代码 

    linux : gcc test.c -fopenmp -lpthread -o test

    #include "stdio.h"
    #include "omp.h"
    #include "time.h"
    #include "unistd.h"
    #include "pthread.h"
    
    clock_t start,end;
    
    void* test(void *p){
    	
    	start = clock();
    	int i;
    	for(i=0;i<100000;i++)
    		usleep(1);				
    
    	end = clock();
    
    	printf("process test    %d
    ",end-start);
    	return ((void *)0);
    }
    
    
    void* test1(void *P){
    	start = clock();
    	int i;
    	#pragma omp parallel for
    	for(i = 0;i<100000;i++)
    		usleep(1);
    	
    	end = clock();
    	printf("process test1   %d
    ",end-start);
    	return ((void *)0);
    
    }
    int main(){
    	
    	int err;
    
    pthread_t ntid;
    pthread_t ntid1;
    void** out;
    
    
    	err = 	pthread_create(&ntid,0,test,0);
    	
    	if(err !=0) putchar('N');
    	err =	pthread_create(&ntid1,0,test1,0);
    	
    	if(err !=0) putchar('N');
    //	test(0);
    //	test1(0);
    	
    	printf("Main process
    ");
    	pthread_join(ntid,out);
    	pthread_join(ntid1,out);
    	
    	
    	return 0;
    
    }
    

      

    windows :

    #include <windows.h>
    #include <iostream>
    #include <process.h>
    #include <time.h>
    
    #define _CRT_SECURE_NO_WARNINGS
    using namespace std;
    
    CRITICAL_SECTION cs;
    
    int i = 0;
    
    void run(void *){
    
    	char num[30];
    	while (1){
    	sprintf(num,"title %d",i++);
    	system(num);
    	Sleep(1000);
    	//MessageBox(0,(LPCTSTR)num,(LPCTSTR) num, 0);
    	}
    	
    }
    
    
    
    int main(){
    
    
    	int hd[4];
    	MessageBoxA(0, "1", "1", 0);
    //	for (int i = 0; i < 4; i++){
    		hd[i] = _beginthread(run, 0, 0);
    //	}
    	WaitForSingleObject(hd, true);
    	system("pause");
    	return 0;
    }
    

      

    参考文献:

    http://www.cnblogs.com/gnuhpc/archive/2012/12/07/2807484.html

    http://blog.csdn.net/zhouruifu2015/article/details/47833985

    http://blog.chinaunix.net/uid-29145190-id-4341878.html

    http://edu.51cto.com/lesson/id-86087.html

  • 相关阅读:
    self 和 super 关键字
    NSString类
    函数和对象方法的区别
    求两个数是否互质及最大公约数
    TJU Problem 1644 Reverse Text
    TJU Problem 2520 Quicksum
    TJU Problem 2101 Bullseye
    TJU Problem 2548 Celebrity jeopardy
    poj 2586 Y2K Accounting Bug
    poj 2109 Power of Cryptography
  • 原文地址:https://www.cnblogs.com/hutiann/p/5965714.html
Copyright © 2011-2022 走看看