| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 533 人关注过本帖
标题:[求助]用到线程的c程序之编译问题
只看楼主 加入收藏
zhaimin889
Rank: 1
等 级:新手上路
帖 子:45
专家分:0
注 册:2006-12-28
收藏
 问题点数:0 回复次数:3 
[求助]用到线程的c程序之编译问题

小生在linux(red hat 9.03)下编了一c程序,程序中用到了pthread_create,pthread_join等函数,编译时出现错误:
pthread_join没定义。#include<pthread.h>我已经写上了。这种情况应该是pthread.h中只用这些函数的声明而没有
具体实现引起的;好像和程序用到cos(),sin()等函数而没有在编译时加上-lm引起的。
不知我说的对不对,若对我该链接哪个库哪?
具体应如何编译哪?假设文件为用户目录下的myThread.c
搜索更多相关主题的帖子: 线程 pthread 编译 函数 
2007-09-08 17:34
百年不亮
Rank: 3Rank: 3
等 级:新手上路
威 望:8
帖 子:789
专家分:0
注 册:2006-4-14
收藏
得分:0 
如果提示你函数没有声明,就是你没有加相应的头文件。
如果提示你没有函数定义,就是你没有指定加载那个库。

用每一个库函数都要考虑下需不需要在编译时指定要链接的库,printf这种常用的不需要指定,线程函数库就需要了,
在编译时加入:-lpthread

2007-09-08 19:39
百年不亮
Rank: 3Rank: 3
等 级:新手上路
威 望:8
帖 子:789
专家分:0
注 册:2006-4-14
收藏
得分:0 
给你个例子你编译试试:
[CODE]
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void task1(int *counter);
void task2(int *counter);
void cleanup(int counter1,int counter2);

int g1=0;
int g2=0;

int main()
{
pthread_t thrd1,thrd2;
int ret;

ret=pthread_create(&thrd1,NULL,(void *)task1,(void*)&g1);
if(ret)
{
perror("pthread_creat : task1");
exit(EXIT_FAILURE);
}

ret=pthread_create(&thrd2,NULL,(void *)task2,(void*)&g2);
if(ret)
{
perror("pthread_creat : task2");
exit(EXIT_FAILURE);
}

pthread_join(thrd2,NULL);
pthread_join(thrd1,NULL);

cleanup(g1,g2);
exit(EXIT_SUCCESS);
}

void task1(int *counter)
{
while(*counter < 5){
printf("task1 count: %d\n",*counter);
(*counter)++;
}
}
void task2(int *counter)
{
while(*counter < 5){
printf("task2 count: %d\n",*counter);
(*counter)++;
}
}

void cleanup(int counter1,int counter2)
{
printf("total iterations : %d",counter1+counter2);
}

[/CODE]

将这个文件命名为thread.c ,然后在shell下这样编译:gcc thread.c -o thread -lpthread
应该不会出错,我已经试过了,编译OK后再执行:./thread
然后,然后你就看到这几个线程的输出了
2007-09-08 19:57
zhaimin889
Rank: 1
等 级:新手上路
帖 子:45
专家分:0
注 册:2006-12-28
收藏
得分:0 
thanks

2007-09-09 18:18
快速回复:[求助]用到线程的c程序之编译问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.024766 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved