Ted's Blog

Happy coding

Linux pthread_create 如何设置 线程的detach 状态

Ted posted @ 2008年9月05日 05:40 in system programming with tags thread , 10255 阅读

1 引言
线程(thread)技术早在60年代就被提出,但真正应用多线程到操作系统中去,是在80年代中期,solaris是这方面的佼佼者。传统的 Unix也支持线程的概念,但是在一个进程(process)中只允许有一个线程,这样多线程就意味着多进程。现在,多线程技术已经被许多操作系统所支 持,包括Windows/NT,当然,也包括Linux。
为什么有了进程的概念后,还要再引入线程呢?使用多线程到底有哪些好处?什么的系统应该选用多线程?我们首先必须回答这些问题。
使用多线程的理由之一是和进程相比,它是一种非常"节俭"的多任务操作方式。我们知道,在Linux系统下,启动一个新的进程必须分配给它独立的 地址空间,建立众多的数据表来维护它的代码段、堆栈段和数据段,这是一种"昂贵"的多任务工作方式。而运行于一个进程中的多个线程,它们彼此之间使用相同 的地址空间,共享大部分数据,启动一个线程所花费的空间远远小于启动一个进程所花费的空间,而且,线程间彼此切换所需的时间也远远小于进程间切换所需要的 时间。据统计,总的说来,一个进程的开销大约是一个线程开销的30倍左右,当然,在具体的系统上,这个数据可能会有较大的区别。
使用多线程的理由之二是线程间方便的通信机制。对不同进程来说,它们具有独立的数据空间,要进行数据的传递只能通过通信的方式进行,这种方式不仅 费时,而且很不方便。线程则不然,由于同一进程下的线程之间共享数据空间,所以一个线程的数据可以直接为其它线程所用,这不仅快捷,而且方便。当然,数据 的共享也带来其他一些问题,有的变量不能同时被两个线程所修改,有的子程序中声明为static的数据更有可能给多线程程序带来灾难性的打击,这些正是编 写多线程程序时最需要注意的地方。
除了以上所说的优点外,不和进程比较,多线程程序作为一种多任务、并发的工作方式,当然有以下的优点:
1) 提高应用程序响应。这对图形界面的程序尤其有意义,当一个操作耗时很长时,整个系统都会等待这个操作,此时程序不会响应键盘、鼠标、菜单的操作,而使用多线程技术,将耗时长的操作(time consuming)置于一个新的线程,可以避免这种尴尬的情况。
2) 使多CPU系统更加有效。操作系统会保证当线程数不大于CPU数目时,不同的线程运行于不同的CPU上。
3) 改善程序结构。一个既长又复杂的进程可以考虑分为多个线程,成为几个独立或半独立的运行部分,这样的程序会利于理解和修改。
下面我们先来尝试编写一个简单的多线程程序。

2 简单的多线程编程
Linux系统下的多线程遵循POSIX线程接口,称为pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,连接 时需要使用库libpthread.a。顺便说一下,Linux下pthread的实现是通过系统调用clone()来实现的。clone()是 Linux所特有的系统调用,它的使用方式类似fork,关于clone()的详细情况,有兴趣的读者可以去查看有关文档说明。下面我们展示一个最简单的 多线程程序example1.c。

/* example.c*/
#include
#include
void thread(void)
{
int i;
for(i=0;i<3;i++)
printf("This is a pthread.n");
}

int main(void)
{
pthread_t id;
int i,ret;
ret=pthread_create(&id,NULL,(void *) thread,NULL);
if(ret!=0){
printf ("Create pthread error!n");
exit (1);
}
for(i=0;i<3;i++)
printf("This is the main process.n");
pthread_join(id,NULL);
return (0);
}

我们编译此程序:
gcc example1.c -lpthread -o example1
运行example1,我们得到如下结果:
This is the main process.
This is a pthread.
This is the main process.
This is the main process.
This is a pthread.
This is a pthread.
再次运行,我们可能得到如下结果:
This is a pthread.
This is the main process.
This is a pthread.
This is the main process.
This is a pthread.
This is the main process.

前后两次结果不一样,这是两个线程争夺CPU资源的结果。上面的示例中,我们使用到了两个函数,  pthread_create和pthread_join,并声明了一个pthread_t型的变量。
pthread_t在头文件/usr/include/bits/pthreadtypes.h中定义:
typedef unsigned long int pthread_t;
它是一个线程的标识符。函数pthread_create用来创建一个线程,它的原型为:
extern int pthread_create __P ((pthread_t *__thread, __const pthread_attr_t *__attr,
void *(*__start_routine) (void *), void *__arg));
第一个参数为指向线程标识符的指针,第二个参数用来设置线程属性,第三个参数是线程运行函数的起始地址,最后一个参数是运行函数的参数。这里,我 们的函数thread不需要参数,所以最后一个参数设为空指针。第二个参数我们也设为空指针,这样将生成默认属性的线程。对线程属性的设定和修改我们将在 下一节阐述。当创建线程成功时,函数返回0,若不为0则说明创建线程失败,常见的错误返回代码为EAGAIN和EINVAL。前者表示系统限制创建新的线 程,例如线程数目过多了;后者表示第二个参数代表的线程属性值非法。创建线程成功后,新创建的线程则运行参数三和参数四确定的函数,原来的线程则继续运行 下一行代码。
函数pthread_join用来等待一个线程的结束。函数原型为:
extern int pthread_join __P ((pthread_t __th, void **__thread_return));
第一个参数为被等待的线程标识符,第二个参数为一个用户定义的指针,它可以用来存储被等待线程的返回值。这个函数是一个线程阻塞的函数,调用它的 函数将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源被收回。一个线程的结束有两种途径,一种是象我们上面的例子一样,函数结束了,调 用它的线程也就结束了;另一种方式是通过函数pthread_exit来实现。它的函数原型为:
extern void pthread_exit __P ((void *__retval)) __attribute__ ((__noreturn__));
唯一的参数是函数的返回代码,只要pthread_join中的第二个参数thread_return不是NULL,这个值将被传递给 thread_return。最后要说明的是,一个线程不能被多个线程等待,否则第一个接收到信号的线程成功返回,其余调用pthread_join的线 程则返回错误代码ESRCH。
在这一节里,我们编写了一个最简单的线程,并掌握了最常用的三个函数pthread_create,pthread_join和pthread_exit。下面,我们来了解线程的一些常用属性以及如何设置这些属性。

3 修改线程的属性
在上一节的例子里,我们用pthread_create函数创建了一个线程,在这个线程中,我们使用了默认参数,即将该函数的第二个参数设为NULL。的确,对大多数程序来说,使用默认属性就够了,但我们还是有必要来了解一下线程的有关属性。
属性结构为pthread_attr_t,它同样在头文件/usr/include/pthread.h中定义,喜欢追根问底的人可以自己去查 看。属性值不能直接设置,须使用相关函数进行操作,初始化的函数为pthread_attr_init,这个函数必须在pthread_create函数 之前调用。属性对象主要包括是否绑定、是否分离、堆栈地址、堆栈大小、优先级。默认的属性为非绑定、非分离、缺省1M的堆栈、与父进程同样级别的优先级。
关于线程的绑定,牵涉到另外一个概念:轻进程(LWP:Light Weight Process)。轻进程可以理解为内核线程,它位于用户层和系统层之间。系统对线程资源的分配、对线程的控制是通过轻进程来实现的,一个轻进程可以控制 一个或多个线程。默认状况下,启动多少轻进程、哪些轻进程来控制哪些线程是由系统来控制的,这种状况即称为非绑定的。绑定状况下,则顾名思义,即某个线程 固定的"绑"在一个轻进程之上。被绑定的线程具有较高的响应速度,这是因为CPU时间片的调度是面向轻进程的,绑定的线程可以保证在需要的时候它总有一个 轻进程可用。通过设置被绑定的轻进程的优先级和调度级可以使得绑定的线程满足诸如实时反应之类的要求。
设置线程绑定状态的函数为pthread_attr_setscope,它有两个参数,第一个是指向属性结构的指针,第二个是绑定类型,它有两个 取值:PTHREAD_SCOPE_SYSTEM(绑定的)和PTHREAD_SCOPE_PROCESS(非绑定的)。下面的代码即创建了一个绑定的线 程。
#include
pthread_attr_t attr;
pthread_t tid;

/*初始化属性值,均设为默认值*/
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);

pthread_create(&tid, &attr, (void *) my_function, NULL);

线程的分离状态决定一个线程以什么样的方式来终止自己。在上面的例子中,我们采用了线程的默认属性,即为非分离状态,这种情况下,原有的线程等待 创建的线程结束。只有当pthread_join()函数返回时,创建的线程才算终止,才能释放自己占用的系统资源。而分离线程不是这样子的,它没有被其 他的线程所等待,自己运行结束了,线程也就终止了,马上释放系统资源。程序员应该根据自己的需要,选择适当的分离状态。设置线程分离状态的函数为pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate)。第二个参数可选为PTHREAD_CREATE_DETACHED(分离线程)和 PTHREAD _CREATE_JOINABLE(非分离线程)。

Avatar_small
afdah 说:
2020年1月13日 17:52

Well, this is definitely an interesting post out there and I would like to know more about it. Let us know if we can include a little bit information about this on our website.
<a href="https://afdah.work/">afdah</a>

Avatar_small
Robinjack 说:
2020年12月18日 03:54

I have prepared this updated practice exam with answers! 50 questions with answers. It will help you succeed in this certification exam abdelahad satour

Avatar_small
Robinjack 说:
2020年12月21日 20:32

Good thinking. Im curious to think what type of impact this would have globally? Sometimes people get a little upset with global expansion. Ill check back to see what you have to say. termite treatments

Avatar_small
Robinjack 说:
2020年12月28日 22:24

Great post, you have pointed out some great points, I besides believe this is a very wonderful website. Buy cocaine online

Avatar_small
SM카지노 说:
2021年1月06日 15:43

Great post, you have pointed out some great points, I besides believe this is a very wonderful website.

Avatar_small
Robinjack 说:
2021年1月08日 19:31

I discovered your blog post web site online and check a number of your early posts. Keep within the very good operate. I recently extra up your Rss to my MSN News Reader. Seeking forward to reading more by you afterwards!… Ross Levinsohn

Avatar_small
Robinjack 说:
2021年1月08日 19:31

if you want to protect the integrity of your heart, then low fat foods should be the thing to go* Ross Levinsohn profile

Avatar_small
Robinjack 说:
2021年1月08日 19:32

Nice post. I find out some thing more challenging on diverse blogs everyday. It will always be stimulating to see content using their company writers and rehearse a specific thing from their store. I’d prefer to use some with all the content on my weblog regardless of whether you do not mind. Natually I’ll provide a link on your web blog. Thank you sharing. Ross Levinsohn cnbc

Avatar_small
Robinjack 说:
2021年1月08日 19:32

Thank you, I have been looking for facts about this topic for ages and yours is the best I’ve discovered so far. Ross Levinsohn

Avatar_small
안전놀이터 说:
2021年1月17日 20:10

Black Ops Zombies… [...]some people still have not played this game. It’s hard to imagine or believe, but yes, some people are missing out on all of the fun.[...]…

Avatar_small
UMAIR 说:
2021年1月21日 19:37

If I had to choose one site,without any confusion I will go through signnow.com/ask/how-to-sign-a-pdf-that-has-already-been-signed-by-someone-else how-to- sign-a-pdf-that-has-already-been-signed-by-someone-else.This is something I've never seen something closer to this in whole internet.No cons at all,loved it!

Avatar_small
FOODS THAT CLEANSE T 说:
2021年1月27日 18:59

Great post, you have pointed out some great points, I besides believe this is a very wonderful website.

Avatar_small
forex trading signal 说:
2021年1月28日 20:56

soem sites that offer download games have viruses and spywares on it. so make sure to have some antivirus on your PC,,

Avatar_small
Daniel Gordon GLD Pa 说:
2021年1月30日 19:57

Good thinking. Im curious to think what type of impact this would have globally? Sometimes people get a little upset with global expansion. Ill check back to see what you have to say.

Avatar_small
Daniel Gordon GLD Pa 说:
2021年1月30日 19:57

Thanks for writing this. I really feel as though I know so much more about this than I did before. Your blog really brought some things to light that I never would have thought about before reading it. You should continue this, Im sure most people would agree youve got a gift.

Avatar_small
Daniel Gordon IMDB 说:
2021年1月30日 19:58

You can definitely see your enthusiasm in the paintings you write. The world hopes for even more passionate writers such as you who are not afraid to say how they believe. Always follow your heart.

Avatar_small
Daniel Gordon GLD Pa 说:
2021年1月30日 19:59

The next occasion I read a weblog, Lets hope it doesnt disappoint me as much as that one. I am talking about, I know it was my method to read, but I really thought youd have some thing fascinating to mention. All I hear is actually a number of whining about something you could fix if you ever werent too busy searching for attention.

Avatar_small
Course hero daniel g 说:
2021年1月30日 20:00

Another thing I have noticed is always that for many people, a bad credit score is the results of circumstances beyond their control. By way of example they may happen to be saddled with illness so they have excessive bills for collections. It can be due to a employment loss or inability to do the job. Sometimes divorce process can truly send the finances in the wrong direction. Thank you for sharing your notions on this site.

Avatar_small
Maven new CEO 说:
2021年1月30日 20:01

I’m new to your blog and i really appreciate the nice posts and great layout.”*~;;

Avatar_small
Ross Levinsohn Maven 说:
2021年1月30日 21:33

Great post, you have pointed out some great points, I besides believe this is a very wonderful website.

Avatar_small
best CBD oils 说:
2021年2月07日 17:44

soem sites that offer download games have viruses and spywares on it. so make sure to have some antivirus on your PC,,

Avatar_small
Robinjack 说:
2021年2月17日 21:45

Some truly nice stuff on this website , I like it. garmisch germany

Avatar_small
Robinjack 说:
2021年2月23日 04:45

That’s a excellent perspective, nonetheless isn’t make every sence whatsoever dealing with which mather. Just about any method with thanks in addition to pondered try and promote your own article straight into delicius nevertheless it is very much a problem in your information sites is it possible i highly recommend you recheck it. gives thanks again. schlüsseldienst preise

Avatar_small
smm panel 说:
2021年2月23日 18:51

soem sites that offer download games have viruses and spywares on it. so make sure to have some antivirus on your PC,,

Avatar_small
amelia 说:
2021年3月13日 00:05

You have a genuine capacity for composing extraordinary substance. I like how you think and the way you speak to your perspectives in this article. I concur with your state of mind. Much obliged to you for sharing.  Buy DMT

Avatar_small
amelia 说:
2021年3月15日 00:25

Extraordinary post, and awesome site. A debt of gratitude is in order for the data!  wholesale ladies shoes

Avatar_small
amelia 说:
2021年3月17日 04:56

Thanks so much for this information.  I have to let you know I concur on several of the points you make here and others may require some further review, but I can see your viewpoint. 토토사이트

Avatar_small
amelia 说:
2021年3月18日 20:37

Your music is astounding. You have some extremely capable specialists. I wish you the best of accomplishment.  wholesale handbag distributors

Avatar_small
amelia 说:
2021年3月18日 20:37

This article is an engaging abundance of educational information that is fascinating and elegantly composed. I compliment your diligent work on this and thank you for this data. You have what it takes to get consideration.  wholesale fashion jewelry accessories

Avatar_small
amelia 说:
2021年3月31日 19:44

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with extra information? It is extremely helpful for me.  สูตรสล็อตทุกค่าย

Avatar_small
amelia 说:
2021年4月01日 01:14

I might want to say this web journal truly persuaded me to do it! Much appreciated, great post.  rent a car čačak

Avatar_small
Asia Gaming 说:
2021年4月07日 18:19

I must appreciate your time and efforts you earn in publishing this blog post. I hope the identical best article by you later on also. Actually your creative writing expertise has encouraged me to start my very own blog site now. Actually the blogging is spreading its wings quickly. Your article is a fine style of it.

Avatar_small
amelia 说:
2021年4月11日 03:55

A debt of gratitude is in order for imparting pleasant data to us. i like your post and all you impart to us is uptodate and very useful, i might want to bookmark the page so i can come here again to peruse you, as you have made a superb showing.  รีวิวUFA800

Avatar_small
chalsea 说:
2021年4月15日 01:47

Great post however I was thinking about whether you could compose a litte more on this subject? I'd be extremely grateful in the event that you could expound a tad bit further. Welcome it!  how to buy a gun online

Avatar_small
chalsea 说:
2021年4月18日 05:47

I know your expertise on this. I must say we should have an online discussion on this. Writing only comments will close the discussion straight away! And will restrict the benefits from this information. guns for sale

Avatar_small
Robinjack 说:
2021年4月24日 21:13

Hello, i feel that i saw you visited my website thus i got here to “return the want”.I’m attempting to find issues to enhance my website!I assume its adequate to make use of some of your concepts!! Monthly Income Review

Avatar_small
chalsea 说:
2021年5月04日 00:52

Howdy! Pleasant stuff, do update me as often as possible when you post again something like this!  linkSiteview

Avatar_small
Monero Mining Pool 说:
2021年5月16日 22:30

Someone essentially help to make significantly articles or blog posts I would state. This really is the first time I frequented your site web page and thus much? I surprised with the research you created to create this distinct publish extraordinary. Amazing job!

Avatar_small
amelia 说:
2021年5月22日 04:13

This is very interesting content!  I have thoroughly enjoyed reading your points and have come to the conclusion that you are right about many of them.  You are great. remoteconnect

Avatar_small
vintage womens cloth 说:
2021年5月26日 13:22

It can be difficult to write about this subject. I think you did a great job though! Thanks for this!

Avatar_small
ch 说:
2021年5月29日 18:07

Super site! I am Loving it!! Will return once more, Im taking your food additionally, Thanks.  click here

Avatar_small
ch 说:
2021年6月06日 02:49

I experience serious difficulties my considerations on substance, however I truly felt I ought to here. Your article is truly awesome. I like the way you composed this data.  website

Avatar_small
Robinjack 说:
2021年6月27日 17:28

You lost me, buddy. I mean, I suppose I get what youre saying. I have an understanding of what you’re saying, but you just appear to have ignored that there are some other individuals within the world who see this issue for what it really is and may not agree with you. You may perhaps be turning away a lot of persons who may have been followers of your website. The Simplest Baccarat Strategy

Avatar_small
Robinjack 说:
2021年6月29日 19:19

I loved as much as you will receive carried out right here. The sketch is attractive, your authored subject matter stylish. nonetheless, you command get got an edginess over that you wish be delivering the following. unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you shield this increase. Slotxo

Avatar_small
Robinjack 说:
2021年7月01日 20:03

First Of All, let me commend your clearness on this subject. I am not an expert on this topic, but after registering your article, my understanding has developed well. Please permit me to take hold of your rss feed to stay in touch with any potential updates. Solid job and will pass it on to supporters and my online readers. How to Gain Baccarat

Avatar_small
Robinjack 说:
2021年7月11日 22:16

You made some decent points there. I looked on the net for any issue and found most individuals goes in addition to with all your website. read more

Avatar_small
HGDFFH 说:
2022年1月03日 16:42

Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info. รีวิวยูฟ่าเบท

Avatar_small
. 카지노사이트 说:
2022年2月19日 01:39

All your hard work is much appreciated. Nobody can stop to admire you. Lots of appreciation. l-arginine benefits for men

Avatar_small
. 카지노사이트 说:
2022年3月14日 02:18

Great things you’ve always shared with us. Just keep writing this kind of posts.The time which was wasted in traveling for tuition now it can be used for studies.Thanks New EV Paint Systems

Avatar_small
. 카지노사이트 说:
2022年3月16日 02:55

Excellent and very exciting site. Love to watch. Keep Rocking. Smm panel

Avatar_small
. 카지노사이트 说:
2022年4月06日 03:45

All your hard work is much appreciated. Nobody can stop to admire you. Lots of appreciation. matka result

Avatar_small
virus 说:
2022年4月21日 18:19

Efficiently written information. It will be profitable to anybody who utilizes it, counting me. Keep up the good work. For certain I will review out more posts day in and day out. 먹튀사이트

Avatar_small
꽁머니 1만 说:
2022年4月21日 19:00

Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work.

Avatar_small
. 카지노사이트 说:
2022年5月01日 03:46

I have bookmarked your blog, the articles are way better than other similar blogs.. thanks for a great blog! flats-for-sale-in-bangalore

Avatar_small
. 카지노사이트 说:
2022年5月02日 04:28

Great articles and great layout. Your blog post deserves all of the positive feedback it’s been getting. ryanair pestle analysis

Avatar_small
. 카지노사이트 说:
2022年6月17日 01:59 Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. There tend to be not many people who can certainly write not so simple posts that artistically. Continue the nice writing Cats
Avatar_small
. 카지노사이트 说:
2022年7月13日 01:07

Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place.. https.//aka.ms/remoteconnect

Avatar_small
IO75L. 说:
2022年7月20日 15:06

<p>
Awesome article, it was exceptionally helpful! I simply began in this and I&#39;m becoming more acquainted with it better! Cheers, keep doing awesome! <a href="https://rattanaxx.livejournal.com/6495.html">https://binaryreviewsrace.com</a></p>

Avatar_small
IO75L. 说:
2022年7月20日 15:07

Awesome article, it was exceptionally helpful! I simply began in this and I'm becoming more acquainted with it better! Cheers, keep doing awesome! https://binaryreviewsrace.com

Avatar_small
. 카지노사이트 说:
2022年7月22日 02:41

It is my first visit to your blog, and I am very impressed with the articles that you serve. Give adequate knowledge for me. Thank you for sharing useful material. I will be back for the more great post. instagram pva accounts

Avatar_small
. 카지노사이트 说:
2022年8月03日 03:04

Thank you for taking the time to publish this information very useful! Search engine specialists Amsterdam Nieuw-West

Avatar_small
dark web/deep web/d 说:
2022年8月04日 01:47

Most people never think twice about it, and many are happy to continue visiting these sites. However, you should always keep in mind that even though you may feel comfortable surfing these sites, there is always a chance that you could become a victim.  dark web links

Avatar_small
dark web/deep web/d 说:
2022年8月04日 02:44

So, just what is the dark web of illegal activity all about? There's a lot more to it than you probably think. Although much of the discussion revolves around Tor, one of the big subjects involves bitcoins, which is also called "bitcoins" by the many who use them for online transactions.  deep web

Avatar_small
dark web/deep web/d 说:
2022年8月04日 03:02

Just because you can't track down someone on the physical side doesn't mean that you can't get their information from their online activities. dark web

Avatar_small
dark web/deep web/d 说:
2022年8月04日 03:16

If someone is thinking about accessing a website with the dark net, they should make sure that it is not a site that was set up to gather personal information.  dark web links

Avatar_small
dark web/deep web/d 说:
2022年8月04日 03:39

When you are visiting another country, it is going to be your own risk. No one else is going to be looking over your shoulder.  dark web sites

Avatar_small
dark web/deep web/d 说:
2022年8月04日 03:54

It offers a variety of services from finding the perfect shoes for your feet to helping you find the best mortgage. If you have not heard of them, you might want to look at their site today. work from home jobs

Avatar_small
dark web/deep web/d 说:
2022年8月04日 04:09

It's really hard to tell which ones are legit and which ones are not. This is why we recommend doing your research before deciding to sign up. affiliate marketing success


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter