神奇的linux:多线程的实现

来源:互联网 发布:万方数据库检索报告 编辑:程序博客网 时间:2024/06/06 00:21

thread.cpp源代码:

#include <stdio.h>// printf#include <pthread.h>// pthread_create#include <stdlib.h>// exit#include <unistd.h> // usleepvoid * thread( void * par){// 线程函数int i;for( i = 0; i < 30; i ++){printf( "This is a pthread.\n");usleep( 1000);}return 0;}int main(void){pthread_t id;int i,ret;ret = pthread_create( &id, NULL, thread, NULL);// 创建一个线程if( ret != 0){printf( "Create pthread error!\n");exit( 1);}for( i = 0; i < 30; i ++){// 和创建的线程并发执行printf( "This is the main process.\n");usleep( 330);}pthread_join( id, NULL); // 等待tid为id的线程退出执行return( 0);}

有时候需要添加 -lstdc++ 才能链接成功。编译:

g++ thread.cpp -lpthread -o thread


0 0
原创粉丝点击