今天我们来利用pthread_create()函数来写一个多线程程序
#include <stdio.h>
#include <pthread.h>
int g_var = 0; /*定义全局变量*/
void *thread_worker1(void *arg)
{
while(1)
{
printf("thread1 g_var=%d",++g_var);
sleep(1);
}
return NULL; /*函数指针返回NULL*/
}
void *thread_worker2(void *arg)
{
while(1)
{
printf("thread2 g_var=%d",++g_var);
sleep(1);
}
return NULL;
}
int main(int argc,char **argv)
{
pthread_t tid1; /*创建两个线程ID*/
pthread_t tid2;
pthread_create(&tid1,NULL,thread_worker1,"haha");
/*pthread_create的四个参数分别为线程ID,线程属性默认NULL,执行函数名,传给该参数的参数*/
printf("start thread_worker1[%lu]\n",tid1); /*用%lu输出无符号长整型整数的线程ID*/
pthread_create(&tid2,NULL,thread_worker2,"xixi");
printf("start thread_worker2[%lu]\n",tid2);
while(1)
{
printf("g_var=%d",++g_var);
sleep(1);
}
return 0;
}
接下来我们看下它的执行结果,注意执行时添加链接
-lpthread,没错,程序会像这样无休无止地运行下去,而且不管线程还是主程序,他们都在对一个全局变量g_var动手脚,而且执行时没有绝对的顺序之分,所以不上锁的话将会造成某些麻烦。我们以后也许会做到对上锁的介绍。
^[[A[lingyun@localhost file]$ gcc pthread-mutex.c -lpthread
[lingyun@localhost file]$ ./a.out
start thread_worker1[3077942128]
start thread_worker2[3067452272]
g_var=1
thread1 g_var=2
thread2 g_var=3
g_var=4
thread1 g_var=5
thread2 g_var=6
g_var=7
thread1 g_var=8
thread2 g_var=9
^C
[lingyun@localhost file]$
最后我们来简单介绍守护进程daemon(),用法为
int daemon(int nochdir, int noclose),第一个参数为0时执行目录变为为根目录,否则不变,第二个参数为0时将标准输入、标准输出和标准出错都重定向到/dev/null,也就是把所有信息放进这个永远装不满的黑洞里,也不会打印到屏幕上,否则的话就是一如既往都不变。
也就是说,我们在程序中添入这样一段程序,就可以将其放入后台。
[lingyun@localhost file]$ gcc pthread-mutex.c -lpthread
[lingyun@localhost file]$ ./a.out
[lingyun@localhost file]$ ps aux | grep a.out
lingyun 11414 0.0 0.0 22596 408 ? Ssl 04:00 0:00 ./a.out
lingyun 11418 0.0 0.0 6052 784 pts/1 S+ 04:00 0:00 grep a.out
[lingyun@localhost file]$
这样,它就被放在后台运行,我们可以轻松找到。