linux c编程 多线程(初级)《转载》---赠人玫瑰,手有余香!
原文地址:http://blog.csdn.net/liang890319/article/details/8393120
进程简单的说就是把一段代码复制成多份,并让他们同时执行。进程间通信是为了让他们有序的运行

线程简单的说就是让多个函数同时执行,线程间通信是为了让他们有序的运行

编译线程程序时会警告说线程函数找不到
pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。
问题解决:
在编译中要加 -lpthread参数
gcc thread.c -o thread -lpthread
thread.c为你些的源文件,不要忘了加上头文件#include<pthread.h>
http://blog.csdn.net/llqkk/article/details/2854558
实例1:创建两个线程,同时执行同一个函数
/* ex7-1.c */
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
void print_msg(char *ptr);
int main()
{
pthread_t thread1, thread2;
int i,j;
char *msg1="do sth1\n";
char *msg2="do sth2\n";
pthread_create(&thread1,NULL, (void *)(&print_msg), (void *)msg1);
pthread_create(&thread2,NULL, (void *)(&print_msg), (void *)msg2);
sleep(1);
return 0;
}
void print_msg(char *ptr)
{
int retval;
int id=pthread_self();
printf("Thread ID: %x\n",id);
printf("%s",ptr);
pthread_exit(&retval);
}
执行gcc ex7-1.c -lpthread
./a.out
实例2 创建多个线程执行不同函数
代码来自 http://www.cnblogs.com/BiffoLee/archive/2011/11/18/2254540.html
#include <pthread.h>
#include <stdio.h>
#include <sys/time.h>
#include <string.h>
#define MAX 10
pthread_t thread[2];
pthread_mutex_t mut;
int number=0, i;
void *thread1()
{
printf ("thread1 : I'm thread 1\n");
for (i = 0; i < MAX; i++)
{
printf("thread1 : number = %d\n",number);
pthread_mutex_lock(&mut);
number++;
pthread_mutex_unlock(&mut);
sleep(2);
}
printf("thread1 :主函数在等我完成任务吗?\n");
pthread_exit(NULL);
}
void *thread2()
{
printf("thread2 : I'm thread 2\n");
for (i = 0; i < MAX; i++)
{
printf("thread2 : number = %d\n",number);
pthread_mutex_lock(&mut);
number++;
pthread_mutex_unlock(&mut);
sleep(3);
}
printf("thread2 :主函数在等我完成任务吗?\n");
pthread_exit(NULL);
}
void thread_create(void)
{
int temp;
memset(&thread, 0, sizeof(thread)); //comment1
//创建线程
if((temp = pthread_create(&thread[0], NULL, thread1, NULL)) != 0) //comment2
printf("线程1创建失败!\n");
else
printf("线程1被创建\n");
if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0) //comment3
printf("线程2创建失败");
else
printf("线程2被创建\n");
}
void thread_wait(void)
{
//等待线程结束
if(thread[0] !=0) { //comment4
pthread_join(thread[0],NULL);
printf("线程1已经结束\n");
}
if(thread[1] !=0) { //comment5
pthread_join(thread[1],NULL);
printf("线程2已经结束\n");
}
}
int main()
{
//用默认属性初始化互斥锁
pthread_mutex_init(&mut,NULL);
printf("我是主函数哦,我正在创建线程,呵呵\n");
thread_create();
printf("我是主函数哦,我正在等待线程完成任务阿,呵呵\n");
thread_wait();
return 0;
}
编译 :
gcc -lpthread -o thread_example lp.c
实例3:信号量控制线程运行顺序
/* thread_sem.c */
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#define THREAD_NUMBER 3
#define REPEAT_NUMBER 3
#define DELAY_TIME_LEVELS 10.0
sem_t sem[THREAD_NUMBER];
void * thrd_func(void *arg)
{
int thrd_num = (int)arg;
int delay_time = 0;
int count = 0;
sem_wait(&sem[thrd_num]);
printf("Thread %d is starting\n", thrd_num);
for (count = 0; count < REPEAT_NUMBER; count++)
{
delay_time = (int)(rand() * DELAY_TIME_LEVELS/(RAND_MAX)) + 1;
sleep(delay_time);
printf("\tThread %d: job %d delay = %d\n", thrd_num, count, delay_time);
}
printf("Thread %d finished\n", thrd_num);
pthread_exit(NULL);
}
int main(void)
{
pthread_t thread[THREAD_NUMBER];
int no = 0, res;
void * thrd_ret;
srand(time(NULL));
for (no = 0; no < THREAD_NUMBER; no++)
{
sem_init(&sem[no], 0, 0);
res = pthread_create(&thread[no], NULL, thrd_func, (void*)no);
if (res != 0)
{
printf("Create thread %d failed\n", no);
exit(res);
}
}
printf("Create treads success\n Waiting for threads to finish...\n");
sem_post(&sem[THREAD_NUMBER - 1]);
for (no = THREAD_NUMBER - 1; no >= 0; no--)
{
res = pthread_join(thread[no], &thrd_ret);
if (!res)
{
printf("Thread %d joined\n", no);
}
else
{
printf("Thread %d join failed\n", no);
}
sem_post(&sem[(no + THREAD_NUMBER - 1) % THREAD_NUMBER]);
}
for (no = 0; no < THREAD_NUMBER; no++)
{
sem_destroy(&sem[no]);
}
return 0;
}
实例4:互斥锁的使用
在这个程序中,一个线程要往缓冲区写数据,另一个线程要读数据,每次只能让一个线程操作缓冲区
/*ex7-3.c*/
#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#define FALSE 0
#define TRUE 1
void readfun();
void writefun();
char buffer[256];
int buffer_has_item=0;
int retflag=FALSE,i=0;
pthread_mutex_t mutex;
int main()
{
void *retval;
pthread_t reader;
pthread_mutex_init(&mutex,NULL);
pthread_create(&reader,NULL,(void *)&readfun,NULL);
writefun();
pthread_join(reader,&retval);
}
void readfun()
{
while(1)
{
if(retflag)
return;
pthread_mutex_lock(&mutex);
if(buffer_has_item==1)
{
printf("%s",buffer);
buffer_has_item=0;
}
pthread_mutex_unlock(&mutex);
}
}
void writefun()
{
int i=0;
while(1)
{
if(i==10)
{
retflag=TRUE;
return;
}
pthread_mutex_lock(&mutex);
if(buffer_has_item==0)
{
sprintf(buffer,"This is %d\n",i++);
buffer_has_item=1;
}
pthread_mutex_unlock(&mutex);
}
}
实例5 条件变量
text
- /* ex7-4.c */
- #include <stdio.h>
- #include <pthread.h>
- #define BUFFER_SIZE 4
- #define OVER (-1)
- struct producers
- {
- int buffer[BUFFER_SIZE];
- pthread_mutex_t lock;
- int readpos, writepos;
- pthread_cond_t notempty;
- pthread_cond_t notfull;
- };
- void init(struct producers *b)
- {
- pthread_mutex_init(&b->lock,NULL);
- pthread_cond_init(&b->notempty,NULL);
- pthread_cond_init(&b->notfull,NULL);
- b->readpos=0;
- b->writepos=0;
- }
- void put(struct producers *b, int data)
- {
- pthread_mutex_lock(&b->lock);
- while((b->writepos+1)%BUFFER_SIZE==b->readpos)
- {
- pthread_cond_wait(&b->notfull,&b->lock);
- }
- b->buffer[b->writepos]=data;
- b->writepos++;
- if(b->writepos>=BUFFER_SIZE) b->writepos=0;
- pthread_cond_signal(&b->notempty);
- pthread_mutex_unlock(&b->lock);
- }
- int get(struct producers *b)
- {
- int data;
- pthread_mutex_lock(&b->lock);
- while(b->writepos==b->readpos)
- {
- pthread_cond_wait(&b->notempty,&b->lock);
- }
- data=b->buffer[b->readpos];
- b->readpos++;
- if(b->readpos>=BUFFER_SIZE) b->readpos=0;
- pthread_cond_signal(&b->notfull);
- pthread_mutex_unlock(&b->lock);
- return data;
- }
- struct producers buffer;
- void *producer(void *data)
- {
- int n;
- for(n=0;n<10;n++)
- {
- printf("Producer : %d-->\n",n);
- put(&buffer,n);
- }
- put(&buffer,OVER);
- return NULL;
- }
- void *consumer(void *data)
- {
- int d;
- while(1)
- {
- d=get(&buffer);
- if(d==OVER) break;
- printf("Consumer: --> %d\n",d);
- }
- return NULL;
- }
- int main()
- {
- pthread_t tha,thb;
- void *retval;
- init(&buffer);
- pthread_create(&tha,NULL,producer,0);
- pthread_create(&thb,NULL,consumer,0);
- pthread_join(tha,&retval);
- pthread_join(thb,&retval);
- return 0;
- }
linux c编程 多线程(初级)《转载》---赠人玫瑰,手有余香!的更多相关文章
- linux串口编程设置(转载)
(转载)在嵌入式Linux中,串口是一个字设备,访问具体的串行端口的编程与读/写文件 的操作类似,只需打开相应的设备文件即可操作.串口编程特殊在于串 口通信时相关参数与属性的设置.嵌入式Linux的串 ...
- Linux网络编程--多线程实现echo服务器与客户端“一对多”功能,是网络编程的“Hello World!”
在linux平台下,用多线程实现echo服务器与客户端“一对多”(即是一台服务器可以响应多个客户端的请求).本人写了个demo,和大家一起分享,有不足的地方,请多多指教,我是壮壮熊. 编译时,在后面加 ...
- Linux系统编程@多线程编程(二)
线程的操作 线程标识 线程的ID表示数据类型:pthread_t (内核中的实现是unsigned long/unsigned int/指向pthread结构的指针(不可移植)几种类型) 1.对两个线 ...
- Linux系统编程@多线程编程(一)
多线程编程 涉及操作系统原理概念 时间片 进程状态 上下文: 对进程来说,就是进程的执行环境,具体就是各个变量和数据,包括所有的寄存器变量.打开的文件.内存信息等. 进程的写时复制:由于一般 fork ...
- Linux系统编程@多线程与多进程GDB调试
博客内容参考自 http://www.cnblogs.com/xuxm2007/archive/2011/04/01/2002162.html http://blog.csdn.net/pbymw8i ...
- Linux系统编程——多线程实现多任务
概述 每一个进程都拥有自己的数据段.代码段和堆栈段.这就造成进程在进行创建.切换.撤销操作时,须要较大的系统开销. 为了降低系统开销,从进程中演化出了线程.为了让进程完毕一定的工作.进程必须至少包括一 ...
- 授人玫瑰 手留余香 --纪念python3.2.3官方文档翻译结束
当你点击看到这篇文章的时候.你已经得到了祝福. 一个来自夜深人静的码农,在2014年5月19号的01:18分.默默为你献上祝福. 希望你.我和他,每个在IT行业中奋斗的人.能找到属于自己一片天空. 在 ...
- Linux系统编程——线程私有数据
在多线程程序中.常常要用全局变量来实现多个函数间的数据共享.因为数据空间是共享的,因此全局变量也为全部线程共同拥有. 測试代码例如以下: #include <stdio.h> #inclu ...
- Linux网络编程入门 (转载)
(一)Linux网络编程--网络知识介绍 Linux网络编程--网络知识介绍客户端和服务端 网络程序和普通的程序有一个最大的区别是网络程序是由两个部分组成的--客户端和服务器端. 客户 ...
随机推荐
- 【HTTP 2】 序言
笔者序 HTTP 2 这个关键词在各大 IT 网站出现频率节节升高,然而出现在大家视野里的,仍以浅析居多.虽有一部分实战(如 InfoQ 之前推送的 iOS App 网络层次架构优化),但针对 HTT ...
- 设计模式(六)桥连模式Bridge(结构型)
设计模式(六)桥连模式Bridge(结构型) 1. 概述 在软件系统中,某些类型由于自身的逻辑,它具有两个或多个维度的变化,那么如何应对这种“多维度的变化”?如何利用面向对象的技术来使得该类型能够 ...
- Java 找出四位数的全部吸血鬼数字 基础代码实例
/** * 找出四位数的全部吸血鬼数字 * 吸血鬼数字是指位数为偶数的数字,能够由一对数字相乘而得到,而这对数字各包括乘积的一半位数的数字,当中从最初的数字中选取的数字能够随意排序. * 以两个 ...
- servlet 将输入内容通过拼接页面的方式显示出来
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...
- img src某个php文件输出图片(回复更改图片readfile读取图片等)
在论坛我们经常看到一回复图片就更改等,这功能是怎么实现的呢,其实更验证码道理相同. 新建文件 randimage.php 加入以下代码: <?php $dir='../../images/'; ...
- android intent收集转载汇总
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS); ComponentName comp = ...
- linux下shutdown无法关闭tomcat进程的解决方式
1.问题 笔者在linux下发现使用tomcat6.0.41自带的./shutdown.sh常常无法停止进程,导致各种问题的发生,令笔者相当反感! 2.解决方式一: 查找到全部的tomcat进程 $ ...
- matlab三维画图
matlab三维画图主要有三个命令:plot3命令.mesh命令和surf命令. plot3 plot3是三维画图的基本函数,绘制的是最为主要的3D曲线图,最主要的调用格式是: plot3(X,Y,Z ...
- Swift - 如何实现字符串的HMAC_SHA1加密
前段时间有个网友问是否有Swift的HMAC_SHA1算法.这次就专门写篇相关文章进行介绍.要说明HMAC-SHA1,首先要先了解什么是HMAC,什么是SHA. 1,HMAC(散列消息身份验证码:Ha ...
- Oracle数据库索引使用及索引失效总结
容易引起oracle索引失效的原因很多: 1.在索引列上使用函数.如SUBSTR,DECODE,INSTR等,对索引列进行运算.需要建立函数索引就可以解决了. 2.新建的表还没来得及生成统计信息,分析 ...