Chinaunix首页 | 论坛 | 博客
  • 博客访问: 176262
  • 博文数量: 27
  • 博客积分: 1649
  • 博客等级: 上尉
  • 技术积分: 274
  • 用 户 组: 普通用户
  • 注册时间: 2010-02-22 22:45
文章分类

全部博文(27)

文章存档

2013年(3)

2012年(5)

2011年(2)

2010年(17)

分类: C/C++

2010-03-26 15:41:03

文件: thread.rar
大小: 0KB
下载: 下载
1、源代码
 

//thread.c

#include <pthread.h>
#include <stdio.h>
void *thread(void *argc)  //返回值为无类型指针变量,参数也为无类型指针变量
{
    int i;
    printf("%s\n",argc);
    for(i=0;i<3;i++)
    {
        printf("This is a pthread.\n");
        sleep(3);
    }
    return ((void *)0);
}
int main(void)
{
    pthread_t id;
    int i,ret;
    ret=pthread_create(&id,NULL,thread,"Hello Thread!"); //创建线程
    if(ret!=0){
        printf ("Create pthread error!\n");
        exit (1);
    }
    for(i=0;i<3;i++) //主线程循环
    {
        printf("This is the main process.\n");
        sleep(1);
    }
    pthread_join(id,NULL);
    return (0);
}

2、函数原型

#include <pthread.h>
int pthread_create(pthread_t *restrict tidp,
                   const pthread_attr_t *restrict attr,
                   void *(*start_rtn)(void *),
                   void *restrict arg);

Returns: 0 if OK, error number on failure


C99 中新增加了 restrict 修饰的指针: 由 restrict 修饰的指针是最初唯一对指针所指向的对象进行存取的方法,仅当第二个指针基于第一个时,才能对对象进行存取。对对象的存取都限定于基于由 restrict 修饰的指针表达式中。 由 restrict 修饰的指针主要用于函数形参,或指向由 malloc() 分配的内存空间。restrict 数据类型不改变程序的语义。 编译器能通过作出 restrict 修饰的指针是存取对象的唯一方法的假设,更好地优化某些类型的例程。

第一个参数为指向线程标识符的指针。
第二个参数用来设置线程属性。
第三个参数是线程运行函数的起始地址(一个返回值是无类型的指针的函数的指针)。
最后一个参数是运行函数的参数。

pthread.h 在/usr/include目录下

3、编译
gcc -o thread thread.c -lpthread

4、说明
如线程运行函数声明为void thread(),则调用时需要强制转换:

ret=pthread_create(&id,NULL,(void *)thread,NULL);


本文参考:http://yecheng110.blog.hexun.com/13030352_d.html
阅读(3925) | 评论(0) | 转发(0) |
1

上一篇:Vim编辑器的一些使用总结

下一篇:wmware

给主人留下些什么吧!~~