提交 f1d5b74c 编写于 作者: B Ben

Update the threading chapter

上级 a99549a1
#include <omp.h>
#include <stdio.h>
#include <stdlib.h> //malloc
#include <string.h> //memset
#include "openmp_getmax.c"
......
/* Compile with:
export CFLAGS="-g -Wall -O3 --std=c11 -pthread -latomic"
make c_factors
*/
#include <pthread.h>
#include <stdatomic.h>
#include <stdlib.h> //malloc
......@@ -44,7 +48,7 @@ void *mark_factors(void *vin){
}
int main(){
long int max = 1e4;
long int max = 1e7;
_Atomic(int) *factor_ct = malloc(sizeof(_Atomic(int))*max);
int thread_ct = 4;
......@@ -58,7 +62,7 @@ int main(){
one_factor_s x[thread_ct];
for (long int i=2; i<= max/2; i+=thread_ct){
for (int t=0; t < thread_ct && t+i <= max/2; t++){
x[t] = (one_factor_s){.i=i+t, .max=max,
x[t] = (one_factor_s){.i=i+t, .max=max,
.factor_ct=factor_ct};
pthread_create(&threads[t], NULL, mark_factors, x+t);
}
......@@ -67,8 +71,8 @@ int main(){
}
int max_factors = get_max_factors(factor_ct, max);
_Atomic(long int) tally[max_factors];
memset(tally, 0, sizeof(long int)*max_factors);
_Atomic(long int) tally[max_factors+1];
memset(tally, 0, sizeof(long int)*(max_factors+1));
tally_s thread_info[thread_ct];
for (int i=0; i< thread_ct; i++){
......@@ -80,6 +84,6 @@ int main(){
for (int t=0; t< thread_ct; t++)
pthread_join(threads[t], NULL);
for (int i=0; i<max_factors; i++)
for (int i=0; i<max_factors+1; i++)
printf("%i\t%li\n", i, tally[i]);
}
/* Compile with:
export CFLAGS="-g -Wall -O3 --std=c11 -pthread -latomic"
make c_primes
*/
#include <stdio.h>
#include <stdatomic.h>
#include <stdlib.h> //malloc
......
......@@ -16,6 +16,7 @@ int main(int argc, char **argv){
argv++;
Stopif(!argc, return 0, "Please give some file names on the command line.");
long int total_wc = 0;
#pragma omp parallel for \
reduction(+:total_wc)
for (int i=0; i< argc; i++){
......
/* Suggested makefile:
----------
P=openmp_atoms
CFLAGS=`pkg-config --cflags glib-2.0` -g -Wall -std=gnu99 -O3 -fopenmp
LDLIBS=`pkg-config --libs glib-2.0` -fopenmp
CFLAGS=-g -Wall -std=gnu99 -O3 -fopenmp
$(P):
----------
......
......@@ -16,6 +16,7 @@ int main(int argc, char **argv){
argv++;
Stopif(!argc, return 0, "Please give some file names on the command line.");
int count[argc];
#pragma omp parallel for
for (int i=0; i< argc; i++){
count[i] = wc(argv[i]);
......
/* Compile with:
export CFLAGS="-g -Wall -O3 --std=c99 -pthread -fopenmp"
make pthread_factors
*/
#include <omp.h> //get_max is still OpenMP
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h> //malloc
#include <string.h> //memset
#include "openmp_getmax.c"
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册