Linux 多线程编程
linux 多线程编程非常简单。
一、多线程编程的流程:
创建线程--->当前线程继续工作--->[与创建的线程同步]--->[等待创建的线程结束与返回]--->当前线程继续工作。
--->创建的线程开始工作--->[与别的线程同步]--->退出线程并返回
线程用的几个主要的函数。
1.线程创建函数:pthread_create(pthread_t * id,pthread_attr_t *attr,void *(*start_routine)(void*),void *arg);
id---线程id ,线程创建成功时的返回值,用于对线程的操作。
attr---线程属性,简单的设为NULL就可以了。
void *(*start_routine)(void*) --- 线程函数,也就工作线程的实际运行部分的代码段。
arg --- 线程参数,是双向的,也就是一个输入输出类型的参数。
2.等待线程返回函数:pthread_join(pthread_t id,void *ret);
id--- 线程id。
ret --- 线程的返回值。
3.退出线程:pthread_exit(void *ret);
ret --- 线程返回值。
一个简单的线程的例子:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_function(void *arg);
char message[] = "Hello World";
int main() {
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_create(&a_thread, NULL, thread_function, (void *)message);
if (res != 0) {
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
printf("Waiting for thread to finish...\n");
res = pthread_join(a_thread, &thread_result);
if (res != 0) {
perror("Thread join failed");
exit(EXIT_FAILURE);
}
printf("Thread joined, it returned %s\n", (char *)thr
相关文档:
2009 年 4 月 23 日
本文中我们针对 Linux 上多线程编程的主要特性总结出 5 条经验,用以改善 Linux 多线程编程的习惯和避免其中的开发陷阱。在本文中,我们穿插一些 Windows 的编程用例用以对比 Linux 特性,以加深读者印象。
背景
Linux 平台上的多线程程序开发相对应其他平台(比如 Windows)的多线程 API 有一些细微 ......
线程(thread)技术早在60年代就被提出,但真正应用多线程到操作系统
中
去,是在80年代中期,solaris
是这方面的佼佼者。传统的Unix
也
支持线程的概念,但是在一个进程
(process)中只允许有一个线程,这样多线程就意味着多进程。现在,多线程技术已经被许多操作系统所
支持,包括Windows/NT,当然,也包括Linux
......
由于LINUX
C没有对字符串子串替换功能,所以我自己写了一个str_replace函数,实现了字符串替换.
请大家参考.
/*
* FUNCTION : str_replace
*
ABSTRACT : replace child string in a string.
*
PARAMETER &nbs ......
在x86 2.4内核下 usleep、select等延时函数无法实现低于10ms延时
而在驱动层在ioctrl中通过udelay、mdelay等等实现延时也无法多进程同时延时
所以实现如下延时函数 能够实现低于10us甚至1us 的延时
unsigned int uDelay(unsigned int delayTime)
{
static struct timeval _tstart, _tend;
static struct timezone ......
Linux操作系统定时任务系统 Cron 入门
cron是一个linux下的定时执行工具,可以在无需人工干预的情况下运行作业。由于Cron 是Linux的内置服务,但它不自动起来,可以用以下的方法启动、关闭这个服务:
/sbin/service crond start //启动服务
/sbin/service crond stop //关闭服务
/sbin/service cr ......