免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 6069 | 回复: 18
打印 上一主题 下一主题

[FreeBSD] 这个简单的多线程程序有问题么? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-05-21 12:12 |只看该作者 |正序浏览
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>


void *smp_line(void *args)
{
   char *s = (char *)args;
   int i;

   pthread_detach(pthread_self());
   for ( ; ; )
      printf("%s", s);

   return NULL;

}


int main()
{
   pthread_t t1, t2;
   char *s1 = "AAAAA";
   char *s2 = "BBBBB";

   if (pthread_create(&t1, NULL, smp_line(s1), NULL)) {
      fprintf(stderr, "Create thread t1 failed!\n");
      abort();
   }

   if (pthread_create(&t2, NULL, smp_line(s2), NULL)) {
      fprintf(stderr, "Create thread t2 failed!\n");
      abort();
   }


   exit(0);
}

在FreeBSD 6.1下编译运行,为什么会一直输出“AAAAAAAAAAAAAAAAAAAA....”呢,我指望它交错输出“AAAAA”和“BBBBB”呢。

[ 本帖最后由 xfsoul 于 2006-5-21 14:52 编辑 ]

论坛徽章:
0
19 [报告]
发表于 2006-08-24 11:08 |只看该作者
原帖由 Momoass 于 2006-6-5 16:22 发表
参数的问题:。

  1. pthread_create(线程结构*,线程属性,执行体*,执行体所需参数*);
复制代码

我已经认识到错误了,真是太惭愧了!

论坛徽章:
0
18 [报告]
发表于 2006-08-24 11:00 |只看该作者
这位同志,我也在做多任务之间的相互切换,能否提点一下?我觉得看不太懂你的例子啊!!!怎么算并行了?

论坛徽章:
0
17 [报告]
发表于 2006-08-07 18:14 |只看该作者
pthread_create(&t1, NULL, smp_line, s1);
pthread_create(&t2, NULL, smp_line, s2);
这样改一下就可以了,楼上的说的完全正确!

论坛徽章:
0
16 [报告]
发表于 2006-06-05 16:22 |只看该作者
参数的问题:。

  1. pthread_create(线程结构*,线程属性,执行体*,执行体所需参数*);
复制代码

[ 本帖最后由 Momoass 于 2006-6-5 17:11 编辑 ]

论坛徽章:
0
15 [报告]
发表于 2006-06-02 17:11 |只看该作者
原帖由 xfsoul 于 2006-5-23 13:24 发表
在ANSI C中,你可以用函数名代替函数指针使用。在适当的场合,编译器会把函数名转化成函数指针。
你自己可以看看《C程序设计语言》去。
我编译是用:gcc -Wall -lpthread thread_test.c
编译的。

你自己先看看吧。

没错 smp_line 是一个函数指针,它的值是一个指向函数的指针。但是 smp_line(s1) 是一个函数调用,它的值是调用 smp_line(s1) 返回的结果,在这里是 void,也就是说这个函数不返回任何值。你的程序严格来说都不应该编译通过的。

pthread_create 接受的是一个指向函数的指针,这个函数返回类型为 void,它有一个参数,类型为 void 型指针。这个参数是通过 pthread_create 的第四个参数传递的。也就是说,如果你打算把 s1 传递给 smp_line,你应该这样调用:

pthread_create(&t2, NULL, smp_line, s1)




PS:还是编程的帖子比较和我的胃口,嘿嘿~

.

[ 本帖最后由 isjfk 于 2006-6-2 17:12 编辑 ]

论坛徽章:
0
14 [报告]
发表于 2006-06-02 16:43 |只看该作者
学习收藏。。。。

论坛徽章:
0
13 [报告]
发表于 2006-05-24 08:23 |只看该作者
You haven't realized you mistake till now.

[ 本帖最后由 antijp 于 2006-5-24 08:27 编辑 ]

论坛徽章:
0
12 [报告]
发表于 2006-05-23 13:24 |只看该作者
在ANSI C中,你可以用函数名代替函数指针使用。在适当的场合,编译器会把函数名转化成函数指针。
你自己可以看看《C程序设计语言》去。
我编译是用:gcc -Wall -lpthread thread_test.c
编译的。

论坛徽章:
0
11 [报告]
发表于 2006-05-22 19:26 |只看该作者
if (pthread_create(&t1, NULL, smp_line(s1), NULL)) {


smp_line(s1) is a pointer to function???? I don't know how can you get such a strange conclusion.

And I can conclude that you didn't ask gcc to strict you behavior(-pedantic or -Wall)
  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP