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\n", 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!\n");
        pthread_mutex_unlock(&mut);
    }
    else
    {
        printf("pthread run already\n");
    }
}

void thread_pause()
{
    if (status == RUN)
    {
        pthread_mutex_lock(&mut);
        status = STOP;
        printf("thread stop!\n");
        pthread_mutex_unlock(&mut);
    }
    else
    {
        printf("pthread pause already\n");
    }
}

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\n");
    if (pthread_cond_init(&cond, NULL) != 0)
        printf("cond init error\n");
#endif

    err = pthread_create(&child_thread, NULL, (void *)thread_function, NULL);
    if (err != 0 )
        printf("can‘t create thread: %s\n", strerror(err));
    while(1)
    {
        printf("father pthread %d\n", 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\n");
    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\n",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\n",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\n");
	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

时间: 2024-08-24 05:34:01

windows 和 linux 多线程的相关文章

windows 与 linux 多线程对应函数

对象 操作 Linux Pthread API Windows SDK 库对应 API 线程 创建 pthread_create CreateThread 退出 pthread_exit ThreadExit 等待 pthread_join WaitForSingleObject 互斥锁 创建 pthread_mutex_init CreateMutex 销毁 pthread_mutex_destroy CloseHandle 加锁 pthread_mutex_lock WaitForSingl

windows和linux/unix多线程的区别

有一面试被问到了windows和linux多线程的区别,特地整理一下,内容全来自网络,如有错误请指正! (1)WIN32里的进程/线程是继承自OS/2的.在WIN32里,“进程”是指一个程序,一般指一个软件,例如Chrome浏览器,但是Chrome会生成好几个后台进程(为了抢占cpu?),一个进程里包含多个线程,用来执行不同的任务,例如Chrome各个不同网页的刷新.WIN32里同一个进程里各个线程之间是共享数据段的,这是与linux系统重要的不同. (2)但是linux系统几乎可以说是没有线程

[转帖]Windows和Linux对决(多进程多线程)

Windows和Linux对决(多进程多线程) https://blog.csdn.net/world_2015/article/details/44920467 太长了 还没看完.. 还是没太理解好呢.. 关于 windows 和 linux的东西 先放这里 晚上有时间仔细啃一下. 并行程序设计分为共享内存和消息驱动(其实就是分布式内存)两种, 共享内存:所有CPU共内存,所有CPU由一个操作系统控制的,例如Windows和Linux/UNIX,目前流行的多核.多CPU机器都是属于这种: 消息

windows和linux套接字中的select机制浅析

先来谈谈为什么会出现select函数,也就是select是解决什么问题的? 平常使用的recv函数时阻塞的,也就是如果没有数据可读,recv就会一直阻塞在那里,这是如果有另外一个连接过来,就得一直等待,这样实时性就不是太好. 这个问题的几个解决方法:1. 使用ioctlsocket函数,将recv函数设置成非阻塞的,这样不管套接字上有没有数据都会立刻返回,可以重复调用recv函数,这种方式叫做轮询(polling),但是这样效率很是问题,因为,大多数时间实际上是无数据可读的,花费时间不断反复执行

socket在windows下和linux下的区别

windows到Linux代码移植遇到的问题 1.一些常用函数的移植 http://www.vckbase.com/document/viewdoc/?id=1586 2.网络 ------ 转载 & 修改(待整理) socket相关程序从windows移植到linux下需要注意的 1)头文件 windows下winsock.h/winsock2.h linux下sys/socket.h 错误处理:errno.h 2)初始化 windows下需要用WSAStartup linux下不需要 3)关

windows和linux进程与线程的理解

对于windows来说,进程和线程的概念都是有着明确定义的,进程的概念对应于一个程序的运行实例(instance),而线程则是程序代码执行的最小单元.也就是说windows对于进程和线程的定义是与经典OS课程中所教授的进程.线程概念相一致的. 提供API,CreateThread()用于建立一个新的线程,传递线程函数的入口地址和调用参数给新建的线程,然后新线程就开始执行了. windows下,一个典型的线程拥有自己的堆栈.寄存器(包括程序计数器PC,用于指向下一条应该执行的指令在内存中的位置),

使用Application Uploader工具在windows、linux下上传iOS App

我们知道发布一个app,一般是用到苹果的application loader助手上传应用,用过的都知道使用起来很繁琐,经常出错.而且只能运行在mac系统上,需要一定的硬件条件. 而上架辅助工具Application Uploader,可以实现在windows,linux或mac上,不需要应用程序加载器和mac计算机,就可以发布app到app store,试用了下,感觉不错,分享给各位开发者,方便大家. Application Uploader是一个专门为IOS app上架的开发助手,可以快速,轻

Windows和linux虚拟机之间联网实现SSH远程连接以及VMware的3种网络模式[NAT、桥接和Host-only]

Windows和linux虚拟机之间联网实现SSH远程连接以及VMware的3种网络模式[NAT.桥接和Host-only] 作者:天齐 一.Windows和linux虚拟机之间联网实现SSH远程连接 假如我们要给主机名为mini1的虚拟机配置ip地址,需要以下几个步骤: 在linux上查看ip地址,如果linux服务器有ip地址,让它的ip地址和windows的ip地址在同一个网段,它们之间才能联网.在linux上查看ip地址的命令为"ifconfig": 发现eth0网卡没有配置i

C语言漫谈(二) 图像显示 Windows和Linux

关于图像显示有很多库可以用,Windows下有GDI,GDI+,D3D等,Linux下有X Window和Wayland,此外还有OpenGL ,SDL等图形库以及各种GUI库. 了解最原始的方式,对于加深理解依然是有帮助的.下面给Windows和Linux下显示位图的最简单例子: Windows用GDI显示图像的例子: 1 /* 2 * FileName: Image_Win.c 3 * Usage: tcc -luser32 -lgdi32 -run Image_Win.c 4 */ 5 6