linux下C语言多线程编程实例
学东西,往往实例才是最让人感兴趣的,老是学基础理论,不动手,感觉没有成就感,呵呵。
下面先来一个实例。我们通过创建两个线程来实现对一个数的递加。
或许这个实例没有实际运用的价值,但是稍微改动一下,我们就可以用到其他地方去拉。
下面是我们的代码:
/*thread_example.c : c multiple thread programming in linux
*author : falcon
*E-mail : tunzhj03@st.lzu.edu.cn
*/
#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)
{
/*等�
相关文档:
由于 Linux 良好的用户权限管理体系,病毒往往是 Linux 系统管理员最后才需要考虑的问题。以往,Linux 上的杀毒软件主要是为企业的邮件和文件服务器所设计的。如今,随着 Linux 桌面用户数量的增长,桌面用户在受益于 Linux 系统对病毒较强的天然免疫力的同时,也需要杀毒软件清理从网络或U盘带来的WIndows病毒。尽管那些 ......
进程是操作系统提供的最古老,最重要的抽象之一,它对开发人员和操作人员隐藏了两个基本的硬件资源:处理器和存储器。进程的重要性在于它营造出个数不受物理处理器限制的虚拟处理器并为每个虚拟处理器配备了独立的,容量不受物理内存大小限制的内存空间。这些虚拟处理器为应用程序模拟出一个和物理处理器几乎相同的环境:每 ......
三个文件,一个头文件,一个读,一个写,用同一个key值申请共享内存。
//shm.h
#ifndef _SHM_COM_H
#define _SHM_COM_H 1
#define TEXT_SZ 2048
struct shared_use_at
{
int written_by_you;
char some_text[TEXT_SZ];
};
struct kts
{
int power;
int mod ......
from:http://www.dzjs.net/html/qianrushixitong/2008/0509/3125.html
1 引言
ELF(Executable and Linkable Format)即可执行连接文件格式,是Linux,SVR4和Solaris2.0默认的目标文件格式,目前标准接口委员会TIS已将ELF标准化为一种可移植的目标文件格式,运行于32-bit Intel体系微机上,可与多种操作 ......