#if 0
1、要求创建两个线程,以及一个全局变量,char str[] = "123456";
要求如下:
1)一个线程专们用于打印str;
2)另外一个线程专们用于倒置str字符串,不使用辅助数组;
3)要求打印出来的结果必须是123456或者654321,不能出现乱序情况
#endif
ubuntu@ubuntu:~/yuyu/yu/8$ gcc 5.c -pthread
ubuntu@ubuntu:~/yuyu/yu/8$ ./a.out
分支线程
str=123456
主线程
str=654321
ubuntu@ubuntu:~/yuyu/yu/8$ cat 5.c
#if 0
1、要求创建两个线程,以及一个全局变量,char str[] = "123456";
要求如下:
1)一个线程专们用于打印str;
2)另外一个线程专们用于倒置str字符串,不使用辅助数组;
3)要求打印出来的结果必须是123456或者654321,不能出现乱序情况
#endif
#if 0
off_t As described in <sys/types.h>.
size_t As described in <stddef.h>.
ssize_t As described in <sys/types.h>.
va_list As described in <stdarg.h>.
#endif
#if 0
[ -Wimplicit-function-declaration ]
[-隐式-函数-声明]
#endif
#include <stdio.h>//printf的函数声明,perror函数声明
//#include <stdlib.h>//用不到这个头文件
//#include <string.h>//字符串用的,这里用不到strcat strlen strcp 才会用到
#include <pthread.h>//implicit declaration of function . pthread cre
//函数的隐式声明PThrecre
#include <unistd.h>//sleep(1)的隐式声明
#if 0
所以用到这几个函数声明:
<stdio.h> <pthread.h> <unistd.h> 3个声明
#endif
char str[]="123456";//定义数组字符串123456
int flag=0;//标志位用flag表示,在主函数外全局变量
void* callback(void *arg)//函数,调用callback//成功返回0,//失败返回非0
{
if(flag == 0)//标志位不变 //打印str
{
printf("分支线程\n");//回掉打印中文
printf("str=%s\n",str);//打印输出字符串,字符串原始值打印出来
flag=1;//标志位变了为1,跳出函数
sleep(1);//沉睡一秒刷新进程,
}
}
int main(int argc, const char *argv[])
{
pthread_t pthpid;//定义一个线程pthpid //创建分支线程
if(pthread_create(&pthpid,NULL,callback,NULL)!=0)//创建线程pthread_create//取地址//线程属性//函数为非0创建失败
//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
#if 0
功能:创建一个线程;
头文件:
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
参数:
pthread_t *thread:该指针指向的内存空间中会存储创建好的线程id号:tid号;
pthread_attr_t *attr:指定线程属性,线程的属性可以通过pthread_attr_init等函数设置,但
是一般填默认属性,即NULL;
void *(*start_routine) (void *):回调函数(函数指针):该指针会指向返回值是void*,参
数列表是void*类型的函数;
void *arg:传递给线程执行体的参数;
返回值:
成功,返回0,
失败,返回错误码,其实就是非0;
#endif
{
perror("pthread");//打印错误码
//function produces a message on standard error describing the last error encountered during a call to a system or
//函数生成一条关于标准错误的消息,该消息描述在调用系统或图书馆函数
return -1;//跟在perror后面
}
sleep(1);//睡一秒刷新进程
if(flag==1)//跳出调用函数执行下面函数
{
printf("主线程\n");//倒置str,把字符串掉头
char *p1=str;//指向字符串第一个指针
char *p2