How to use pthread_create && mutex?
2024-10-01 03:59:59
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
最新文章
- spring 整合 mongo
- Vue之计算属性
- rtc关机闹钟2 Alarm manager
- 解决Odoo出现的Unable to send email, please configure the sender&#39;s email address or alias.
- 【Python之路Day12】网络篇之Python操作MySQL
- 高德地图JavaScript API开发研究
- Android2.3.7源码结构分析
- 关于最大流的EdmondsKarp算法详解
- Java 字节码
- GetLastError来获得错误信息转成文本描述
- Visual Studio 2010多线程编程
- win快捷键
- centos7之关于时间和日期以及时间同步的应用
- 安卓使用TextView实现图片加文字说明
- C#导出Excel时间格式问题
- 动态规划之132 Palindrome Partitioning II
- 【17】迭代器模式(Iterator Pattern)
- sysdig
- mysql实现oracle sequence方案
- 最佳的MongoDB客户端管理工具
热门文章
- HDU 4509
- 从Eclipse到Android Studio:Android项目怎样进行迁移
- pthread_rwlock pthread读写锁
- MySql免安装版l配置方法
- 代理server的理解(1):Windows环境下的代理server设置
- bzoj 1045 [HAOI2008] 糖果传递 —— 贪心
- 【题解】【CodeForces712C】Memory and De-Evolution
- .Net Core(二) 下
- RPC与REST
- 偶尔遇到的“The request was aborted:Could not create SSL/TLS secure channel.”怎么解决?