使用pthread_create()创建线程

可以通过 pthread_create()函数创建新线程。

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

返回值:
若成功,返回0;否则,返回错误编码

参数说明:

  • tidp:新创建的线程ID会被设置成tidp指向的内存单元。
  • attr:用于定制各种不能的线程属性,默认为NULL
  • start_rtn:新创建的线程从start_rtn函数的地址开始运行,该函数只有一个void类型的指针参数即arg,如果start_rtn需要多个参数,可以将参数放入一个结构中,然后将结构的地址作为arg传入。

pthread函数在调用失败后通常会返回错误码,但不会设置errno

我们看下面一个例子,该示例中,程序创建了一个线程,打印了进程ID、新线程的线程ID以及初始线程的线程ID。

#include <pthread.h>

pthread_t ntid;

void printids(const char *s)
{
	pid_t	pid;
	pthread_t	tid;
	
	pid = getpid();
	tid = pthread_self();

	printf("%s pid %lu tid %lu (0x%lx)
", s, (unsigned long)pid, (unsigned long)tid, (unsigned long)tid);
}

void* thr_fn(void *arg)
{
	printids("new thread:");
	return((void*)0);
}

int main()
{
	int 	err;
	
	err = pthread_create(&ntid, NULL, thr_fn, NULL);
	if(err!=0)
	{
		printf("can't create thread
");
		exit(1);
	}
	printids("main thread:");
	sleep(2);
	exit(0);
}

运行结果如下:

main thread: pid 13019 tid 139937898653440 (0x7f45d4bd6700)
new thread: pid 13019 tid 139937890158336 (0x7f45d43bc700)

正如我们的期望,进程ID相同10310,线程ID不同。

主线程如果不休眠,有可能在新线程执行之前就退出了。

如下是去掉后的再次执行结果,很明显,第一次执行时,新线程没有机会运行:

➜  tmp ./pt
main thread: pid 13113 tid 139742167656192 (0x7f1842436700)
➜  tmp ./pt
main thread: pid 13119 tid 139768977393408 (0x7f1e803f8700)
new thread: pid new thread: pid 13119 tid 139768968922880 (0x7f1e7fbe4700)

上面示例中,我们使用pthread_self()函数获得线程的ID

原文地址:https://www.cnblogs.com/biggerman/p/6940888.html