linux c/c++多线程程序的编写

第一次尝试编写linux下多线程程序,也是颇废一番周折。深知初学者对能快速的成功运行一段程序的渴望,所以本文专门用了“linux c/c++多线程程序的编写“这个醒目的标题,方便大家能即使从搜索引擎搜到本文,从而提升大家的信心。
首先先让代码进行起来再说为什么,见了效果再回过来头来看原因似乎会容易明白和理解一些。
测试代码如下:

#include[stdio.h]
#include[unistd.h]
#include[stdlib.h]
#include[pthread.h]
#include[string.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 (0 != res) {
        perror("Thread creation faied");
        exit(EXIT_FAILURE);
    }
 
    printf("Waiting for thread to finish...\n");
    res = pthread_join(a_thread, &thread_result);
    if (0 != res) {
        perror("Thread join failed");
        exit(EXIT_FAILURE);
    }
    printf("Thread joined, it returned %s\n", (char*)thread_result);
    printf("Message is now %s\n",message);
    exit(EXIT_FAILURE);
}
void *thread_function(void* arg) {
    printf("thread_function is running. argument was %s\n",(char*)arg);
    sleep(3);
    strcpy(message,"bye!");
    pthread_exit("Thank you for the cpu time");
}

请将包含头文件的[替换成< ,]替换成>,代码高亮插件会认为尖括号是html标签,所以这里用中括号暂时替代。
编译:

hqlong@ubuntu:~/code/c$ gcc test.c -o test -lpthread

运行

hqlong@ubuntu:~/code/c$ ./test

结果

thread_function is running. argument was Hello world!
Waiting for thread to finish...
Thread joined, it returned Thank you for the cpu time
Message is now bye!

创建进程主要是通过pthread_create()这个函数来创建,函数的定义如下:

int pthread_create
(
	pthread_t *restrict tidp,
	const pthread_attr_t *restrict attr,
	void *(*start_rtn)(void),
	void *restrict arg
);

返回值:若是成功建立线程返回0,否则返回错误的编号
形式参数:
pthread_t *restrict tidp 要创建的线程的线程id指针
const pthread_attr_t *restrict attr 创建线程时的线程属性
void* (start_rtn)(void) 返回值是void类型的指针函数
vodi *restrict arg start_rtn的行参

注意上面还用到了pthread_join()这个函数,那么这个函数有什么用呢?接下来还是先看看它的原形定义:

int pthread_join
(
	pthread_t thread,
	void **value_ptr
);

各参数说明如下:
thread 等待退出线程的线程号
value_ptr 退出线程的返回值。
该函数的作用使得当前进程挂起,等待另一个进程返回才继续执行。也就是说当程序运行到这个地方时,程序会先停止,然后等线程id为thread的这个线程返回,然后程序才会断续执行。

在上面的例子中,如果把

  res = pthread_join(a_thread, &thread_result);
    if (0 != res) {
        perror("Thread join failed");
        exit(EXIT_FAILURE);
    }
    printf("Thread joined, it returned %s\n", (char*)thread_result);

注释掉,那么主程序根据不会等待线程返回,就退出,当然主进行退出了,他所创建的子进程也就会跟着退出,所以在上面的例子中,程序还在睡眠时,就被主进程强行退出了。

在上面例子进对源码进行编译时,加了-lpthread,如果不加-lprhead,会出现如下编译错误。

tmp/ccnPVTWo.o: In function `main':
mthread.c:(.text+0x30): undefined reference to `pthread_create'
mthread.c:(.text+0x6f): undefined reference to `pthread_join'
collect2: ld returned 1 exit status

thread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a。

更多细节请参考:
http://hi.baidu.com/wenlongren/blog/item/4615450f498006eaaa645759.html
http://hi.baidu.com/wenlongren/blog/item/998f04dd7e866de877c6383e.html
http://blog.sina.com.cn/s/blog_5dcf190f0100dbcm.html
http://hi.baidu.com/beisika/blog/item/8ced51cea7ac9c3eb600c8ea.html

机器人 2009-06-08 18:00 于 北京 阴
机器人 2009-06-09 10:48 于 北京 晴 更新

此条目发表在 c/c++, linux/server 分类目录,贴了 , , 标签。将固定链接加入收藏夹。

linux c/c++多线程程序的编写》有 22 条评论

  1. Hey, nice post, very well written. You should post more about this.

  2. gives employ a perfect web page decent Gives with thanks for the work to assist everyone

  3. Hello, Wouldn’t it be probable make use of this excellent write-up on my website?I’d naturally link back to you. Let me discover what you determine to perform.

  4. My mate and I really liked reading material on this page, I was just interested to acknowledge if you trade featured posts? I am always seeking to find individuals to make trades with but it’s just a thought I would ask.

  5. Pingback 引用通告: Dubstep Software

  6. Pingback 引用通告: learn and earn online

  7. Pingback 引用通告: financial news

  8. Pingback 引用通告: business buy sell

  9. Bond 说:

    I ran across your weblog on bing and look some of the early articles. Keep up the superb work. Seeking to reading through more of your stuff later on!…

  10. Pingback 引用通告: toddcardin.com

  11. Pingback 引用通告: toddcardin.org

  12. Pingback 引用通告: toddcardin.info

  13. Pingback 引用通告: toddcardin.net

  14. Pingback 引用通告: web designer doncaster

  15. Pingback 引用通告: iphone sim only contracts

  16. Pingback 引用通告: Snow Joe SJ620

  17. Pingback 引用通告: best halloween creative ideas and horror artwork

  18. Pingback 引用通告: best free designs

  19. Pingback 引用通告: This is why this video will make you like Indie Euro Rock again!

  20. Pingback 引用通告: fashion cinemagraphs

发表评论

电子邮件地址不会被公开。 必填项已用*标注

您可以使用这些HTML标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>