利用pthread_create()写一个多线程程序并放到后台运行

今天我们来利用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]$ 

这样,它就被放在后台运行,我们可以轻松找到。



  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

姜亚轲

你花钱的样子真帅

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值