Unix/Linux下C语言POSIX多线程程序示例

    原想用fork机制来实现多个任务并发的, 结果始终没有搞定其中的数据共享问题, 就换成用POSIX线程算了.

#include <pthread.h>
#include <stdio.h>

void *subCall(void *param)
{
  int *p = param;
  (*p) ++;
  return NULL;
}

int main()
{
   int i, *p=NULL;
   int err;
   pthread_t pid;
   p = (int *) malloc(sizeof(int));
   *p = 10;
   for(i=0;i<3;i++)
   {
       err=pthread_create(&pid, NULL , subCall, p);
       sleep(1);
       printf("wait 1 second! -- err=%d, tid=%d, val=%d\n\n", err,pid, (*p));
   }
   free(p);
   return 0;
}

    在编译时要加上"-lpthread", 否则的话程序不能工作在多线程模式下.

gcc -o test -l pthread test.c

    目标是由线程来将主程序中的数据加一, 结果完成我的要求.

wait 1 second! -- err=0, tid=4, val=11

wait 1 second! -- err=0, tid=6, val=12

wait 1 second! -- err=0, tid=7, val=13

    好象线程模式更容易理解啊.

留言 (3)

你准备用这个玩意儿干啥?

在我的一个新工具中用, 为了保护自已, 得用C/OCI来写这些工具啊.

gcc -o test -l pthread test.c
孩子笔误吧,快改过来!

发表留言:

« Previous | Main | Next »

英语900句 | English 900

  • Would you be so kind as to lend me some money?
  • 你能借我一点儿钱吗?
  • No problem. How much?
  • 没问题, 你要多少?
  • I hope I'm not bothering you.
  • 我希望我没有打扰你.
  • I hope that will not cause you too much trouble.
  • 我希望那不会给你添太多麻烦.
  • I really appreciate your help.
  • 我非常感谢你的帮助.