1

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h> void *thread_function(void *arg)
{
int i;
for (i=0; i<5; i++){
printf("Thread says hi!\n");
sleep(1);
}
return NULL;
} int main(void)
{
pthread_t mythread; if ( pthread_create( &mythread, NULL, thread_function, NULL) ){
printf("error creating thread.\n");
abort();
} if ( pthread_join( mythread, NULL )){
printf("error joining thread.");
abort();
} exit(0);
}
gcc -o pthread1 pthread1.c -lpthread

2

#cat thread2.c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> int myglobal; void *thread_function(void *arg)
{
int i,j;
for (i=0; i<20; i++){
i=myglobal;
j=j+1;
printf(".");
fflush(stdout);
sleep(1);
myglobal=j;
}
return NULL;
} int main(void)
{
pthread_t mythread;
int i; if (pthread_create(&mythread, NULL, thread_function, NULL)){
printf("Error creating thread.");
abort();
} for (i=0; i<20; i++){
myglobal=myglobal+1;
printf("o");
fflush(stdout);
sleep(1);
} if (pthread_join(mythread, NULL)){
printf("Error joining.");
abort();
} printf("\nmyglobal equals %d\n ",myglobal);
exit(0);
}

3. Use mutex

#cat thread3.c
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h> int myglobal; pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER; void *thread_function(void *arg)
{
int i,j;
for (i=0; i<10; i++){
pthread_mutex_lock(&mymutex);
j=myglobal;
j=j+1;
printf(".");
fflush(stdout);
sleep(1);
myglobal=j;
pthread_mutex_unlock(&mymutex);
} return NULL;
} int main(void)
{
pthread_t mythread;
int i;
if (pthread_create(&mythread, NULL, thread_function, NULL)){
printf("Error creating function;");
abort();
} for (i=0; i<10; i++){
pthread_mutex_lock(&mymutex);
myglobal=myglobal+1;
pthread_mutex_unlock(&mymutex);
printf("o");
fflush(stdout);
sleep(1);
} if (pthread_join(mythread, NULL)){
printf("Error joining thread.");
abort();
} printf("myglobal equals %d\n",myglobal);
exit(0);
}

REF

https://www.ibm.com/developerworks/cn/linux/thread/posix_thread2/index.html

最新文章

  1. spring 整合 mongo
  2. Vue之计算属性
  3. rtc关机闹钟2 Alarm manager
  4. 解决Odoo出现的Unable to send email, please configure the sender&#39;s email address or alias.
  5. 【Python之路Day12】网络篇之Python操作MySQL
  6. 高德地图JavaScript API开发研究
  7. Android2.3.7源码结构分析
  8. 关于最大流的EdmondsKarp算法详解
  9. Java 字节码
  10. GetLastError来获得错误信息转成文本描述
  11. Visual Studio 2010多线程编程
  12. win快捷键
  13. centos7之关于时间和日期以及时间同步的应用
  14. 安卓使用TextView实现图片加文字说明
  15. C#导出Excel时间格式问题
  16. 动态规划之132 Palindrome Partitioning II
  17. 【17】迭代器模式(Iterator Pattern)
  18. sysdig
  19. mysql实现oracle sequence方案
  20. 最佳的MongoDB客户端管理工具

热门文章

  1. HDU 4509
  2. 从Eclipse到Android Studio:Android项目怎样进行迁移
  3. pthread_rwlock pthread读写锁
  4. MySql免安装版l配置方法
  5. 代理server的理解(1):Windows环境下的代理server设置
  6. bzoj 1045 [HAOI2008] 糖果传递 —— 贪心
  7. 【题解】【CodeForces712C】Memory and De-Evolution
  8. .Net Core(二) 下
  9. RPC与REST
  10. 偶尔遇到的“The request was aborted:Could not create SSL/TLS secure channel.”怎么解决?