Linux多线程编程

==============================================================
【程序1】WaitForMultipleObjects.cpp
运行结果:
created 0 ok
Hi
created 1 ok
world
main thread

linux下交叉编译exe需要:
ftp://sourceware.org/pub/pthreads-win32/dll-latest

//# g++ -o WaitForMultipleObjects WaitForMultipleObjects.cpp -lpthread
//# i586-mingw32msvc-gcc -o WaitForMultipleObjects.exe WaitForMultipleObjects.cpp -lpthreadGC2
#include <unistd.h>//sleep

#include <pthread.h>
#include <stdio.h>

unsigned int ChildFunc(void *pParam)
{
	int num=*(int *)pParam;
	// Do some
#if WIN32
	Sleep((2*num+2)*1000);//单位为毫秒
#else
	sleep(2*num+2);//单位为秒
#endif	
	if(num==0)
	printf("Hi\n");
	if(num==1)
	printf("world\n");
	// Task finished
	//_endthreadex(0);
	//return 0;
}

int main(int argc, char *argv[])
{
	pthread_t h_thread[2];
	int j[2]={0,1};
	for(int i=0;i<2;i++)
	{
		//h_thread[i]=(HANDLE)::_beginthreadex(NULL,0,(PBEGINTHREADEX_THREADFUNC)ChildFunc,&j[i], 0, (unsigned int *)&thread_ID);
		//h_thread[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFunc,&j[i],0,&thread_ID);//also OK
		int ret=pthread_create(&h_thread[i], NULL, (void *(*)(void *))ChildFunc, &j[i]);
		if(ret==0)
		{
			printf("created %d ok\n", i); // Creating 2 asynchronous tasks
			pthread_join(h_thread[i],NULL);
		}
	}
	//WaitForMultipleObjects(2,h_thread,TRUE,INFINITE);//监测多个对象
	printf("main thread\n");
#if WIN32
	getchar();
#endif	
	return 0;
} 

==============================================================

【程序2】WaitForMultipleObjects2.cpp
运行结果:
root@iZ14rcmneyrcltZ:~/cpptest# g++ -std=c++11 -o WaitForMultipleObjects2 WaitForMultipleObjects2.cpp -lpthread

root@iZ14rcmneyrcltZ:~/cpptest# ./WaitForMultipleObjects2
Hi
world
main thread:
#include <unistd.h>//sleep

//#include <pthread.h>
#include <thread>
#include <stdio.h>

unsigned int ChildFunc(void *pParam)
{
int num=*(int *)pParam;
// Do some
sleep(2*num+2);
if(num==0)
printf("Hi\n");
if(num==1)
printf("world\n");
return 0;
}

int main(int argc, char *argv[])
{
std::thread workerThreads[2];
int j[2]={0,1};
for (int i=0; i<2; ++i)
{
workerThreads[i] = std::thread(ChildFunc, &j[i]);
}
for (auto& workerThread : workerThreads)
{
workerThread.join();
}
printf("main thread\n");

return 0;
}
==============================================================
【程序3】

pthread_join.c
运行结果:
gcc pthread_join.c -lpthread -o pthread_join
./pthread_join
...
This is Child Thread: 1335
This is Parent Thread: 1079
...
This is Parent Thread: 1521
This is Child Thread: 1522
...
This is Child Thread: 1998
rval= 0
/*
pthread_join, pthread_exit
*/

#include <stdio.h>
#include <pthread.h>
#include <errno.h>

typedef void * (*THREADFUNC)();

//全局变量g从0加到1998
int g;
unsigned long ChildProcess(void* p)
{
for (int i = 1; i < 1000; i ++) {
g ++;
printf( "This is Child Thread: %d\n", g );
}
//ExitThread(0);
//_endthreadex(0);
pthread_exit((void*)0); //线程退出
return 0;
};

int main(int argc, char * argv [ ])
{
int iRet = 0;
void *rval = NULL;
pthread_t pid1;
g = 0;
//CreateThread( NULL, 0, ChildProcess, NULL, 0, &threadID );
//HANDLE hThrd = (HANDLE)_beginthreadex(NULL,0,(PBEGINTHREADEX_THREADFUNC)ChildProcess,(LPVOID)1,0,(unsigned int *)&threadID);
iRet = pthread_create(&pid1, NULL, (THREADFUNC)ChildProcess, NULL); //创建一个线程
if(0 != iRet)
{
printf("pthread_create error, %s,%d\n", (char *)strerror(errno), errno);
return -1;
}
else {
printf("Thread launched\n");
}
for (int i = 1; i < 1000; i ++) {
g ++;
printf( "This is Parent Thread: %d\n", g );
}
pthread_join(pid1, &rval); //线程等待,线程退出的值存放在rval中
printf("rval= %d\n", (int)rval);

return 0;
}

==============================================================
【程序4】GetTickCount.c

gcc GetTickCount.c -lpthread -o GetTickCount
./GetTickCount
/*
pthread_join, pthread_exit,clock_gettime
*/

#include <stdio.h>
#include <pthread.h>
#include <errno.h>
#include <time.h>

// 返回自系统开机以来的毫秒数(tick)
unsigned long GetTickCount()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
}

typedef void * (*THREADFUNC)();

unsigned long ThreadFunc(void* p)
{
int val;

for (int i=0; i<100; i++)
{
for (int j=0; j<100; j++)
{
val=i*j;
printf("i=%d,j=%d,i*j=%d\n",i,j,val);
}
}

return 0;
};

int main(int argc, char * argv [ ])
{
unsigned long begin;
unsigned long elapsed;
printf("CLOCK_MONOTONIC=%d\n",CLOCK_MONOTONIC);
printf("sizeof(unsigned int)=%d\n",sizeof(unsigned int));
printf("sizeof(unsigned long)=%d\n",sizeof(unsigned long));
printf("sizeof(void *)=%d\n",sizeof(void *));
printf("sizeof(long long)=%d\n",sizeof(long long));

puts("Timing normal function call...");
begin = GetTickCount();
ThreadFunc(0);
elapsed = GetTickCount()-begin;
printf("Function call took: %d.%.03d seconds\n\n",elapsed/1000, elapsed%1000);//0.092 seconds
//return 0;
puts("Timing thread + busy loop...");
begin = GetTickCount();

int iRet = 0;
void *rval = NULL;
pthread_t pid1;
iRet = pthread_create(&pid1, NULL, (THREADFUNC)ThreadFunc, NULL); //创建一个线程
if(0 != iRet)
{
printf("pthread_create error, %s,%d\n", (char *)strerror(errno), errno);
return -1;
}
else {
printf("Thread launched\n");
}
pthread_join(pid1, &rval); //线程等待,线程退出的值存放在rval中
elapsed = GetTickCount()-begin;
printf("Thread + busy loop took: %d.%.03d seconds\n",elapsed/1000, elapsed%1000);//0.092 seconds~3.057 seconds

return 0;
}
==============================================================
【程序5】lock.c

运行结果:
gcc lock.c -lpthread -o lock
./lock
Thread i=0 launched
Thread i=1 launched
num1:127530675 num2:127530675

//# g++ -o lock lock.cpp -lpthread
//# i586-mingw32msvc-gcc -o lock.exe lock.cpp -lpthreadGC2
#include <unistd.h>//sleep
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>

typedef void * (*THREADFUNC)(void *);

//全局变量
long num1=0,num2=0;
int bContinue=1;

//CRITICAL_SECTION cs; //新建一CRITICAL_SECTION
pthread_mutex_t mylock1;

unsigned int ThreadFunc(void *pParam)
{
	while(bContinue)
	{
		//EnterCriticalSection(&cs); //进入CRITICAL_SECTION
		int intResult1 = pthread_mutex_lock(&mylock1);
		num1++;
		num2++;
		pthread_mutex_unlock(&mylock1);
		//LeaveCriticalSection(&cs); //退出CRITICAL_SECTION
	}
	return 0;
}

int main(int argc, char *argv[])
{
	pthread_mutex_init(&mylock1, NULL);
	int iRet[2] = {0};
	void *rval[2] = {NULL,NULL};
	pthread_t pid[2]= {0};
	for(int i=0;i<2;i++)
	{
		iRet[i] = pthread_create(&pid[i], NULL, (THREADFUNC)ThreadFunc, NULL);
		if(0 != iRet[i])
		{
			printf("pthread_create i=%d error, %s,%d\n",i, (char *)strerror(errno), errno);
			pthread_mutex_destroy(&mylock1);
			return -1;
		}
		else {
			printf("Thread i=%d launched\n",i);
		}
	}
#if WIN32
    Sleep(3000);
#else
    sleep(3);
#endif 	
	bContinue=0;
	pthread_join(pid[0], &rval[0]);
	pthread_join(pid[1], &rval[1]);
	//DeleteCriticalSection(&cs); //销毁CRITICAL_SECTION
	printf("num1:%d\tnum2:%d\n",num1,num2);

	pthread_mutex_destroy(&mylock1);	
#if WIN32
	getchar();
#endif	
	return 0;
}

==============================================================
【程序6】lock_guard.cpp

运行结果:
g++ lock_guard.cpp -lpthread -o lock_guard
./lock_guard
product 1
product 2
consume 1
product 3
product 4
consume 2
product 5
product 6
consume 3
product 7
product 8
consume 4
product 9
consume 5
consume 6
consume 7
consume 8
consume 9
consume 0
consume 0
...

#include <iostream>
#include <thread>
#include <mutex>
#include <deque>
//#include <condition_variable>
#include <unistd.h>

class CThreadMsg
{
private:
std::deque<int> m_data;
std::mutex m_mtx; // 全局互斥锁.
//std::condition_variable m_cv; // 全局条件变量.
int m_nGen;

public:

void send_all()
{
//m_cv.notify_all();
}

void send(){
//std::unique_lock <std::mutex> lck(m_mtx);
std::lock_guard <std::mutex> lck(m_mtx);
m_nGen = ++m_nGen % 1000;
printf("product %d\n", m_nGen);
m_data.push_back(m_nGen);
//lck.unlock();
//m_cv.notify_one();
}

void ConsumerRecv(){
while (true){
sleep(2);
//std::unique_lock <std::mutex> lck(m_mtx);
std::lock_guard <std::mutex> lck(m_mtx);
/* while (m_data.empty()){
m_cv.wait(lck);
} */
int nData = m_data.front();
m_data.pop_front();
printf("consume %d\n", nData);
//lck.unlock();
}
}

CThreadMsg(){
m_data.clear();
m_nGen = 0;
}

virtual ~CThreadMsg()
{
send_all();

}

void Start(){
std::thread t(&CThreadMsg::ConsumerRecv, this);
t.detach();

}
};


int main()
{
CThreadMsg test;
test.Start();
int i = 10;
while(1)
{
i--;
if(i> 0)
test.send();
sleep(1);
}
return 0;
}
==============================================================
【程序7】

posted on 2020-03-02 20:53  梦回第四帝国  阅读(223)  评论(0)    收藏  举报

导航