Testing with MySQL embedded

Size: px
Start display at page:

Download "Testing with MySQL embedded"

Transcription

1 Testing with MySQL embedded by Roberto Polli Integration Testing is not always common between C developers. MySQL API offer us a fast and pratical way to do it using a full-featured, dummy sql embedded server. Obviously an embedded server has its limitations, eg: no replication; one process at a time; missing more logic (eg. mysqldump...) but you can implement it. See mysql embedded documentation for further info! The MySQL C API To access a MySQL server from a C program, we can use the API provided by MySQL. Functions are provided by the following library files. Client: /usr/lib/libmysqlclient.so standard version /usr/lib/libmysqlclient_r.so Server embedded: /usr/lib/mysql/libmysqld.a - reentrant version You can use /usr/bin/mysql_config to set the build flags. That s the standard output of #mysql_config Usage: /usr/bin/mysql_config [OPTIONS] Options: --cflags [-I/usr/include/mysql -DBIG_JOINS=1 -fno-strictaliasing -DUNIV_LINUX -DUNIV_LINUX] --include [-I/usr/include/mysql] --libs [-Wl,-Bsymbolic-functions -rdynamic -L/usr/lib/mysql - lmysqlclient] --libs_r [-Wl,-Bsymbolic-functions -rdynamic -L/usr/lib/mysql - lmysqlclient_r] --plugindir [/usr/lib/mysql/plugin] --socket [/var/run/mysqld/mysqld.sock]

2 --port [0] --version [5.1.41] --libmysqld-libs [-Wl,-Bsymbolic-functions -rdynamic -L/usr/lib/mysql - lmysqld -ldl -lwrap -lrt] Here is the anatomy of a MySQL client application: uses a shared library and the external server. My test application occupy about 200KBytes. An embedded app is bigger, because it s statically linked with the mysqld library. It s an almost complete MySQL server instance! And it s faster! Basic working cycle with a MySQL Server The simplest way to connect to MySQL consists to: - initialize mysql library - connect to server - execute queries, eventually freeing result sets - disconnect

3 Here is a sample program with some assertions, that show us the expected return values of the functions. #include<assert.h> #include<stdlib.h> #include<mysql/mysql.h> int main(int argc, char**argv) { int port = 0, mysql_option_flags=0; char *host = localhost, *user = mysql, *pass = secret, *dbname = NULL, *unix_sock = NULL; // Initialize mysql library. This should be done *once* // moreover this function is not thread-safe, nor reentrant // so we should protect it with a global mutex assert( mysql_library_init(0, NULL, NULL) == 0 ); MYSQL * mysql = NULL; // a pointer to a mysql database structure // Inizialize mysql database structure, containing all database informations // this function is not thread-safe too assert( (mysql = mysql_init(null))!= NULL); // connect to the RDBMS without specifying a database name int error = mysql_real_connect(mysql, host, user, pass, dbname, port, unix_sock, mysql_option_flags); // eventually print errors if (error) goto onerror; // do our job error = mysql_query(mysql, CREATE DATABASE pluto; );

4 if (error) goto onerror; error = mysql_query(mysql, USE pluto; ); if (error) goto onerror; error = mysql_query(mysql, DROP DATABASE pluto; ); if (error) goto onerror; // disconnet and free memory and resources mysql_close(mysql); mysql_library_end(); exit(0); onerror: printf( Error: %s\n, mysql_error(mysql)); abort(); Going multithreads Using multiple threads - and multiple connections - require some logic. In fact the following functions must be called at once in the process - and must be protected by a global mutex: 1. mysql_library_init() 2. mysql_init() which may call mysql_library_init() Other MySQL methods are thread safe per-connection : the MYSQL* pointer is associated to a reference the connection. So every MYSQL* pointer can be used by a single thread at once, requiring us to do use some locking. Let s create the following database structure, a global mutex and some helper methods. // a locking structure for each connection typedef struct my_db { MYSQL * mysql; pthread_mutex_t lock; int lock_init; char* user; char* pass; char* host; char* dbhost; char* unix_sock;

5 int port; int options; mysql_db; // a mutex for global calls pthread_mutex_t db_global_mutex = PTHREAD_MUTEX_INITIALIZER; The structure simply ties the database connection parameters, its MYSQL structure and a mutex that makes it thread safe. The global mutex avoid us to call mysql_init() in different threads. Here are some methods, the missing ones are left as an exercise to the reader. We will add a my_flush_result() method, *required* to clean resultset after queries. Please see MySQL documentation for further info about it!. Non connection-safe functions There are two ways to protect the non thread-safe functions: call them in the main thread, before spawning the others; or use our global mutex. The mysql_library_init() should be called once by EVERY thread using mysql - so it s better to run it in the main(), before spawning threads. Similarly you have to run mysq_library_end() at the end of the process to free memory resources. In the same way, we can allocate all our connection before running the client threads - creating a connection pool and passing it to our threads. /** * creating a connection pool */ int main(int argc, char** argv) { // some variables int i=0, pool_size = 5; mysql_db my_pool[pool_size]; // once in the process, so no mutexes mysql_library_init(0, NULL, NULL); // again...no locks for (i=0; i<pool_size; i++) {

6 // fill the my_pool with credential, user, passwd......initialize_db_structure(&my_pool[i]);... // initialize lock pthread_mutex_init(&my_pool[i].lock); &my_pool[i]->lock_initialized = TRUE; //initialize db &my_pool[i]->mysql = mysql_init(null); pass &my_pool[i] to threads and run them... mysql_library_end(); Otherwise we just have to protect each call with our global mutex and run our sequence at every connection... mysql_db* my_init(mysql_db *db) { /// initialize mutex, WARN can t initialize it twice, /// so check if you have already initialized it! if (!db->lock_initialized) { pthread_mutex_init(&db->lock, NULL); db->lock_initialized=true; /// initialize mysql structure pthread_mutex_lock(&db->lock); // don t use this db while initializing pthread_mutex_lock(&db_global_mutex); // don t initialize two databases contemporarily db->mysql = mysql_init(null); pthread_mutex_unlock(&db_global_mutex); pthread_mutex_unlock(&db->lock); return db;

7 Connection-safe functions Connection safe functions are now easy: just lock and unlock the MYSQL* pointer in use, to have consistent values for results, counters and errors. int my_connect(mysql_db *db) { pthread_mutex_lock(&db->lock); int error = mysql_real_connect(db->mysql, db->host, db->user, db->pass, db->dbname, db->port, db->unix_sock, db->options); if (error) { printf( Error: %s\n, mysql_error(db->mysql)); /// release lock *after* mysql_error pthread_mutex_unlock(&db->lock); return error; int my_query(mysql_db* db, char*query) { pthread_mutex_lock(&db->lock); error = mysql_query(db->mysql, query); if (error) { printf( Error: %s\n, mysql_error(db->mysql)); else { if (mysql_field_count(db->mysql) == 0) { rows = mysql_affected_rows(db->mysql); printf("%lld rows affected\n",rows ); pthread_mutex_unlock(&db->lock); return error; /** * clean result */ int my_flush_result(mysql_db *db) { MYSQL *mysql = db->mysql; MYSQL_RES* result; int qstatus = 0;

8 pthread_mutex_lock(&db->lock); do { if ((result = mysql_store_result(mysql))) { mysql_free_result(result); if (mysql_field_count(mysql) == 0) { printf("%lld rows affected\n",mysql_affected_rows(mysql)); else { printf("could not retrieve result set\n"); break; if ((qstatus = mysql_next_result(mysql)) > 0) printf("could not execute statement\n"); while(qstatus == 0); pthread_mutex_unlock(&db->lock); return qstatus; So we ve just create a simple MySQL client! Once you ve understood the common pitfalls, it s not so hard! Testing with a MySQL server Once we created our simple MySQL library, we can write our client code issuing some queries and printing reports. Provided we ve a working MySQL server, we can create some test cases. First of all we ll create the setup() and teardown() methods to prepare our environment. void setup(mysql_db *db) { mysql_library_init(0,null,null); db = my_init(db); my_connect(db); my_query(db, create database pippo; ); my_query(db, use pippo; ); void teardown(mysql_db *db) {

9 my_query(db, drop database pippo; ); my_close(db); mysql_library_end(); Then we create a simple test case, which issues a lot of insert. Note that this code is shortened for better readability! void test_sql_client(mysql_db *db) { int i, error; error = my_query(db, create table t1( \ id int not null auto_increment primary key \, value varchar(25)); ); for (i=0; i<10000; i++) { error = my_query(db, insert into t1(id,value) values ( %d, prova%d );, i, i); my_flush_result(db); int main(int argc, char**argv) { mysql_db *db = calloc(sizeof(mysql_db));...set db values... setup(db); test_sql_client(db); teardown(db); free(db); exit(exit_success); To build our program, mysql_test.c we issue #gcc mysql_test.c -o mysql_test $(mysql_config --libs) and with time we ll see how long will it take to run 10k insert. Note that this will include setup and teardown time. Writing a more complete test is left as an exercise to the reader ;)

10 # time./mysql_test What s MySQL embedded To run the previous file, named mysql_test.c, we need a working MySQL instance. Instead if we don t have it - or we like more isolation and speed, we could use the MySQL embedded. Using MySQL embedded means you don t need to connect to a server, but you ll write directly into the MySQL database files. And it s fast! To use MySQL embedded, you just need to link your file with the mysqld library: #gcc mysql_test.c -o mysql_test $(mysql_config --libmysqld-libs) The server instructions will be added to your program, which will increase its size. While the core client code remains the same, you need to modify a bit your initialization structure, passing some parameters to the mysql_library_init() function. Those parameters are the same that you would pass to mysqld server process, eg. --datadir=path. If you have never run MySQL server by command line, or you re not familiar with my.conf please, take some time to play with it before continuing. In our case we should only modify the setup() function to reflect our changes. Before that we need to sketch the MySQL database directory structure. MySQL directory structure MySQL stores databases and authentication information in the /var/lib/mysql directory. The forementioned database would have the following structure: /var/lib/mysql/ mysql <- the core database containing user/password credentials pippo <- a newly created database By default, MySQL embedded will use the /var/lib/mysql directory, so interfering with our server and requiring RW access to /var/lib/mysql. This is usually not what we want. Instead we want to put everything in another place, eg. a temporary directory under /tmp/. So when we run the embedded server, we should create a new directory and tell it to bootstrap there a new MySQL installation. Let s do it.

11 Bootstrapping MySQL embedded To run the embedded server we need to provide: a directory where to store the new mysql databases; the parametes to run the embedded server; the server groups. Server groups are the stanzas of my.conf file from which mysqld - and our embedded application - read configuration options. A typical my.conf files has the following structure: [mysqld]...options for server... [embedded]...options for the embedded server... [server]...options for server... To specify custom parameters relative to our application, we could add the following sections to our my.conf, or - with more isolation - use another my.conf containing the specified sections. [embedded]...options for *all* embedded applications... key_buffer_size=32m [xxx_server]...replace xxx with program name (eg. argv[0]) and add options for this specific program datadir=/tmp/ [xxx_client]...replace xxx with program name (eg. argv[0]) and add options for this specific program... datadir=/tmp We can even specify those parameters as arguments to the mysql_server_init()

12 void embedded_mysql_library_init(char* progname) { /// create a temporary directory where to store the db char *datadir = strdup("/tmp/mysqlembedxxxxxx"); assert( mkdtemp(datadir)!=null ); /// prepare server parameters const char *server_options[] = { progname, /* this string is not used */ "-h", datadir, "--key_buffer_size=32m", "--bootstrap", // create the required mysql files NULL ; int num_elements = sizeof(server_options) / sizeof(char *) -1; /// create server groups for my.cnf sprintf(progname_client, "%s_client", progname); sprintf(progname_server, "%s_server", progname); char *server_groups[] = { progname_server, progname_client, "embedded", NULL // end of arguments ; /// initialize the embedded server assert(mysql_library_init(num_elements, (char**) server_options, server_groups) == 0); void embedded_my_init(mysql_db *db) { pthread_mutex_lock(&db->lock, NULL); /// initialize and set options assert( (mysql = mysql_init(db->mysql))!= NULL ); assert( mysql_options(db->mysql, MYSQL_READ_DEFAULT_GROUP, progname_client) == 0); assert( mysql_options(db->mysql, MYSQL_OPT_USE_EMBEDDED_CONNECTION, NULL) == 0);

13 pthread_mutex_unlock(&db->lock, NULL); return db; With our new methods, the setup function become: void setup(mysql_db *db, char* progname) { embedded_mysql_library_init(progname); db = embeded_my_init(db); // from here everything is the same my_connect(db); my_query(db, create database pippo; ); my_query(db, use pippo; ); And our new main(): int main(int argc, char**argv) { mysql_db *db = calloc(sizeof(mysql_db));...set db values... setup(db, argv[0]); test_sql_client(db); teardown(db); exit(exit_success); Replacing the old one with this one, everything will work nicely in both cases. When you link against libmysqlclient, all the different initialization variables - only applicable to embedded server - are ignored. Duplicate test files with embedded sql To run both tests you have to compile twice your software: #gcc mysql_test.c -o mysql_server_test $(mysql_config --libs)

14 #gcc mysql_test.c -o mysql_embedded_test $(mysql_config --libmysqld-libs) Now you have two executables, one using the client connection, one the embedded server. Here are some speed results for 50k INSERTs run locally on my Laptop. You re welcome to provide further stats for SELECT, UPDATE, INSERT or UPDATE and TRANSACTIONS! CPU: 2 x Intel(R) Core(TM)2 Duo RAM: 8Gb MySQL Server InnoDB 21 sec MySQL Server MemoryDB 7sec MySQL Embedded InnoDB 5.7 sec MySQL Embedded MemoryDB 5.6 sec

15 Licenza d'uso Attribuzione - Non commerciale - Non opere derivate, secondo i criteri internazionali Creative Commons (

Lab 6-1: MySQL Server

Lab 6-1: MySQL Server Lab 6-1: MySQL Server 1. Objective The participants of the course will be able to: Install and configure a MySQL server. Define a c-program, which enables to access (write and read) to the database of

More information

CPSC 421 Database Management Systems. Lecture 10: Embedded SQL

CPSC 421 Database Management Systems. Lecture 10: Embedded SQL CPSC 421 Database Management Systems Lecture 10: Embedded SQL * Some material adapted from R. Ramakrishnan, L. Delcambre, and B. Ludaescher Today s Agenda Quiz Project Part 2 Embedded SQL DDL and DML Notes:

More information

How to get MySQL to fail

How to get MySQL to fail Snow B.V. Feb 3, 2013 Introduction We all know we shouldn t press the button... Introduction We all know we shouldn t press the button... but we all want to try. Do you know? Do you know what happens if

More information

CS 3305 Intro to Threads. Lecture 6

CS 3305 Intro to Threads. Lecture 6 CS 3305 Intro to Threads Lecture 6 Introduction Multiple applications run concurrently! This means that there are multiple processes running on a computer Introduction Applications often need to perform

More information

Kaivos User Guide Getting a database account 2

Kaivos User Guide Getting a database account 2 Contents Kaivos User Guide 1 1. Getting a database account 2 2. MySQL client programs at CSC 2 2.1 Connecting your database..................................... 2 2.2 Setting default values for MySQL connection..........................

More information

Programs. Function main. C Refresher. CSCI 4061 Introduction to Operating Systems

Programs. Function main. C Refresher. CSCI 4061 Introduction to Operating Systems Programs CSCI 4061 Introduction to Operating Systems C Program Structure Libraries and header files Compiling and building programs Executing and debugging Instructor: Abhishek Chandra Assume familiarity

More information

Procedures, Parameters, Values and Variables. Steven R. Bagley

Procedures, Parameters, Values and Variables. Steven R. Bagley Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.

More information

Oracle 1Z MySQL 5.6 Database Administrator. Download Full Version :

Oracle 1Z MySQL 5.6 Database Administrator. Download Full Version : Oracle 1Z0-883 MySQL 5.6 Database Administrator Download Full Version : http://killexams.com/pass4sure/exam-detail/1z0-883 D. The mysqld binary was not compiled with SSL support. E. The server s SSL certificate

More information

Software Development With Emacs: The Edit-Compile-Debug Cycle

Software Development With Emacs: The Edit-Compile-Debug Cycle Software Development With Emacs: The Edit-Compile-Debug Cycle Luis Fernandes Department of Electrical and Computer Engineering Ryerson Polytechnic University August 8, 2017 The Emacs editor permits the

More information

Lecture 03 Bits, Bytes and Data Types

Lecture 03 Bits, Bytes and Data Types Lecture 03 Bits, Bytes and Data Types Computer Languages A computer language is a language that is used to communicate with a machine. Like all languages, computer languages have syntax (form) and semantics

More information

HPCSE - I. «Introduction to multithreading» Panos Hadjidoukas

HPCSE - I. «Introduction to multithreading» Panos Hadjidoukas HPCSE - I «Introduction to multithreading» Panos Hadjidoukas 1 Processes and Threads POSIX Threads API Outline Thread management Synchronization with mutexes Deadlock and thread safety 2 Terminology -

More information

SmartHeap for Multi-Core

SmartHeap for Multi-Core SmartHeap for Multi-Core Getting Started and Platform Guide for Linux Version 11.2 SmartHeap and HeapAgent are trademarks of Compuware Corporation. All other trademarks are the property of their respective

More information

Fall 2015 COMP Operating Systems. Lab #3

Fall 2015 COMP Operating Systems. Lab #3 Fall 2015 COMP 3511 Operating Systems Lab #3 Outline n Operating System Debugging, Generation and System Boot n Review Questions n Process Control n UNIX fork() and Examples on fork() n exec family: execute

More information

MySQL Architecture and Components Guide

MySQL Architecture and Components Guide Guide This book contains the following, MySQL Physical Architecture MySQL Logical Architecture Storage Engines overview SQL Query execution InnoDB Storage Engine MySQL 5.7 References: MySQL 5.7 Reference

More information

ENCM 501 Winter 2019 Assignment 9

ENCM 501 Winter 2019 Assignment 9 page 1 of 6 ENCM 501 Winter 2019 Assignment 9 Steve Norman Department of Electrical & Computer Engineering University of Calgary April 2019 Assignment instructions and other documents for ENCM 501 can

More information

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary GATE- 2016-17 Postal Correspondence 1 C-Programming Computer Science & Information Technology (CS) 20 Rank under AIR 100 Postal Correspondence Examination Oriented Theory, Practice Set Key concepts, Analysis

More information

COMP 2355 Introduction to Systems Programming

COMP 2355 Introduction to Systems Programming COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Functions Similar to (static) methods in Java without the class: int f(int a, int

More information

Common Misunderstandings from Exam 1 Material

Common Misunderstandings from Exam 1 Material Common Misunderstandings from Exam 1 Material Kyle Dewey Stack and Heap Allocation with Pointers char c = c ; char* p1 = malloc(sizeof(char)); char** p2 = &p1; Where is c allocated? Where is p1 itself

More information

Exercise Session 2 Systems Programming and Computer Architecture

Exercise Session 2 Systems Programming and Computer Architecture Systems Group Department of Computer Science ETH Zürich Exercise Session 2 Systems Programming and Computer Architecture Herbstsemester 216 Agenda Linux vs. Windows Working with SVN Exercise 1: bitcount()

More information

SQL Data Definition Language: Create and Change the Database Ray Lockwood

SQL Data Definition Language: Create and Change the Database Ray Lockwood Introductory SQL SQL Data Definition Language: Create and Change the Database Pg 1 SQL Data Definition Language: Create and Change the Database Ray Lockwood Points: DDL statements create and alter the

More information

PRINCIPLES OF OPERATING SYSTEMS

PRINCIPLES OF OPERATING SYSTEMS PRINCIPLES OF OPERATING SYSTEMS Tutorial-1&2: C Review CPSC 457, Spring 2015 May 20-21, 2015 Department of Computer Science, University of Calgary Connecting to your VM Open a terminal (in your linux machine)

More information

Tutorial 1 C Tutorial: Pointers, Strings, Exec

Tutorial 1 C Tutorial: Pointers, Strings, Exec TCSS 422: Operating Systems Institute of Technology Spring 2017 University of Washington Tacoma http://faculty.washington.edu/wlloyd/courses/tcss422 Tutorial 1 C Tutorial: Pointers, Strings, Exec The purpose

More information

Chapter 8: Working With Databases & Tables

Chapter 8: Working With Databases & Tables Chapter 8: Working With Databases & Tables o Working with Databases & Tables DDL Component of SQL Databases CREATE DATABASE class; o Represented as directories in MySQL s data storage area o Can t have

More information

Copyright 2008, Sun Microsystems. MySQL 5.1 for ISV / OEM Solutions

Copyright 2008, Sun Microsystems. MySQL 5.1 for ISV / OEM Solutions Copyright 2008, Sun Microsystems MySQL 5.1 for ISV / OEM Solutions Table of Contents A MySQL Technical White Paper 1 Executive Summary...3 2 The MySQL Embedded Server and OEM Applications...3 3 What s

More information

CS107, Lecture 9 C Generics Function Pointers

CS107, Lecture 9 C Generics Function Pointers CS107, Lecture 9 C Generics Function Pointers Reading: K&R 5.11 This document is copyright (C) Stanford Computer Science and Nick Troccoli, licensed under Creative Commons Attribution 2.5 License. All

More information

What Is A Process? Process States. Process Concept. Process Control Block (PCB) Process State Transition Diagram 9/6/2013. Process Fundamentals

What Is A Process? Process States. Process Concept. Process Control Block (PCB) Process State Transition Diagram 9/6/2013. Process Fundamentals What Is A Process? A process is a program in execution. Process Fundamentals #include int main(int argc, char*argv[]) { int v; printf( hello world\n ); scanf( %d, &v); return 0; Program test

More information

C Grundlagen - Threads

C Grundlagen - Threads Michael Strassberger saremox@linux.com Proseminar C Grundlagen Fachbereich Informatik Fakultaet fuer Mathematik, Informatik und Naturwissenschaften Universitaet Hamburg 3. Juli 2014 Table of Contents 1

More information

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14 BIL 104E Introduction to Scientific and Engineering Computing Lecture 14 Because each C program starts at its main() function, information is usually passed to the main() function via command-line arguments.

More information

COSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14

COSC 2P91. Introduction Part Deux. Week 1b. Brock University. Brock University (Week 1b) Introduction Part Deux 1 / 14 COSC 2P91 Introduction Part Deux Week 1b Brock University Brock University (Week 1b) Introduction Part Deux 1 / 14 Source Files Like most other compiled languages, we ll be dealing with a few different

More information

My malloc: mylloc and mhysa. Johan Montelius HT2016

My malloc: mylloc and mhysa. Johan Montelius HT2016 1 Introduction My malloc: mylloc and mhysa Johan Montelius HT2016 So this is an experiment where we will implement our own malloc. We will not implement the world s fastest allocator, but it will work

More information

FAT (32 KB) 216 * 215 = 231 = 2GB

FAT (32 KB) 216 * 215 = 231 = 2GB The Microsoft FAT 16 file system (supported by all of Microsoft's operating systems from latter versions of MS-DOS through Windows8, as well as all Linux versions) is an example of a file allocation table

More information

211: Computer Architecture Summer 2016

211: Computer Architecture Summer 2016 211: Computer Architecture Summer 2016 Liu Liu Topic: C Programming Structure: - header files - global / local variables - main() - macro Basic Units: - basic data types - arithmetic / logical / bit operators

More information

COMP s1 Lecture 1

COMP s1 Lecture 1 COMP1511 18s1 Lecture 1 1 Numbers In, Numbers Out Andrew Bennett more printf variables scanf 2 Before we begin introduce yourself to the person sitting next to you why did

More information

CSE 153 Design of Operating Systems Fall 2018

CSE 153 Design of Operating Systems Fall 2018 CSE 153 Design of Operating Systems Fall 2018 Lecture 4: Processes (2) Threads Process Creation: Unix In Unix, processes are created using fork() int fork() fork() Creates and initializes a new PCB Creates

More information

Financial computing with C++

Financial computing with C++ Financial Computing with C++, Lecture 6 - p1/24 Financial computing with C++ LG Gyurkó University of Oxford Michaelmas Term 2015 Financial Computing with C++, Lecture 6 - p2/24 Outline Linked lists Linked

More information

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7

CS 220: Introduction to Parallel Computing. Input/Output. Lecture 7 CS 220: Introduction to Parallel Computing Input/Output Lecture 7 Input/Output Most useful programs will provide some type of input or output Thus far, we ve prompted the user to enter their input directly

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 11: Memory, Files and Bitoperations (yaseminb@kth.se) Overview Overview Lecture 11: Memory, Files and Bit operations Main function; reading and writing Bitwise Operations Lecture 11: Memory, Files

More information

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto Ricardo Rocha Department of Computer Science Faculty of Sciences University of Porto Adapted from the slides Revisões sobre Programação em C, Sérgio Crisóstomo Compilation #include int main()

More information

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016

CS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016 CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable

More information

CS-345 Operating Systems. Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization

CS-345 Operating Systems. Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization CS-345 Operating Systems Tutorial 2: Grocer-Client Threads, Shared Memory, Synchronization Threads A thread is a lightweight process A thread exists within a process and uses the process resources. It

More information

Introduction: The Unix shell and C programming

Introduction: The Unix shell and C programming Introduction: The Unix shell and C programming 1DT048: Programming for Beginners Uppsala University June 11, 2014 You ll be working with the assignments in the Unix labs. If you are new to Unix or working

More information

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco CS 326 Operating Systems C Programming Greg Benson Department of Computer Science University of San Francisco Why C? Fast (good optimizing compilers) Not too high-level (Java, Python, Lisp) Not too low-level

More information

Load Data Fast! BILL KARWIN PERCONA LIVE OPEN SOURCE DATABASE CONFERENCE 2017

Load Data Fast! BILL KARWIN PERCONA LIVE OPEN SOURCE DATABASE CONFERENCE 2017 Load Data Fast! BILL KARWIN PERCONA LIVE OPEN SOURCE DATABASE CONFERENCE 2017 Bill Karwin Software developer, consultant, trainer Using MySQL since 2000 Senior Database Architect at SchoolMessenger SQL

More information

Array Initialization

Array Initialization Array Initialization Array declarations can specify initializations for the elements of the array: int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ; initializes primes[0] to 2, primes[1] to 3, primes[2]

More information

CS354 gdb Tutorial Written by Chris Feilbach

CS354 gdb Tutorial Written by Chris Feilbach CS354 gdb Tutorial Written by Chris Feilbach Purpose This tutorial aims to show you the basics of using gdb to debug C programs. gdb is the GNU debugger, and is provided on systems that

More information

CS342 - Spring 2019 Project #3 Synchronization and Deadlocks

CS342 - Spring 2019 Project #3 Synchronization and Deadlocks CS342 - Spring 2019 Project #3 Synchronization and Deadlocks Assigned: April 2, 2019. Due date: April 21, 2019, 23:55. Objectives Practice multi-threaded programming. Practice synchronization: mutex and

More information

Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview

Computer Science 322 Operating Systems Mount Holyoke College Spring Topic Notes: C and Unix Overview Computer Science 322 Operating Systems Mount Holyoke College Spring 2010 Topic Notes: C and Unix Overview This course is about operating systems, but since most of our upcoming programming is in C on a

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Winter 2009 Lecture 7 Introduction to C: The C-Level of Abstraction CSE 303 Winter 2009, Lecture 7 1 Welcome to C Compared to Java, in rough

More information

Introduction to MySQL Cluster: Architecture and Use

Introduction to MySQL Cluster: Architecture and Use Introduction to MySQL Cluster: Architecture and Use Arjen Lentz, MySQL AB (arjen@mysql.com) (Based on an original paper by Stewart Smith, MySQL AB) An overview of the MySQL Cluster architecture, what's

More information

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science Functions in C C Programming and Software Tools N.C. State Department of Computer Science Functions in C Functions are also called subroutines or procedures One part of a program calls (or invokes the

More information

EECE.4810/EECE.5730: Operating Systems Spring 2017 Homework 2 Solution

EECE.4810/EECE.5730: Operating Systems Spring 2017 Homework 2 Solution 1. (15 points) A system with two dual-core processors has four processors available for scheduling. A CPU-intensive application (e.g., a program that spends most of its time on computation, not I/O or

More information

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24

Memory Management. a C view. Dr Alun Moon KF5010. Computer Science. Dr Alun Moon (Computer Science) Memory Management KF / 24 Memory Management a C view Dr Alun Moon Computer Science KF5010 Dr Alun Moon (Computer Science) Memory Management KF5010 1 / 24 The Von Neumann model Memory Architecture One continuous address space Program

More information

Computer Systems Assignment 2: Fork and Threads Package

Computer Systems Assignment 2: Fork and Threads Package Autumn Term 2018 Distributed Computing Computer Systems Assignment 2: Fork and Threads Package Assigned on: October 5, 2018 Due by: October 12, 2018 1 Understanding fork() and exec() Creating new processes

More information

SQL (and MySQL) Useful things I have learnt, borrowed and stolen

SQL (and MySQL) Useful things I have learnt, borrowed and stolen SQL (and MySQL) Useful things I have learnt, borrowed and stolen MySQL truncates data MySQL truncates data CREATE TABLE pets ( id INT UNSIGNED NOT NULL AUTO_INCREMENT, type CHAR(3) NOT NULL, PRIMARY KEY

More information

CMPT 300. Operating Systems. Brief Intro to UNIX and C

CMPT 300. Operating Systems. Brief Intro to UNIX and C CMPT 300 Operating Systems Brief Intro to UNIX and C Outline Welcome Review Questions UNIX basics and Vi editor Using SSH to remote access Lab2(4214) Compiling a C Program Makefile Basic C/C++ programming

More information

Load Testing Tools. for Troubleshooting MySQL Concurrency Issues. May, 23, 2018 Sveta Smirnova

Load Testing Tools. for Troubleshooting MySQL Concurrency Issues. May, 23, 2018 Sveta Smirnova Load Testing Tools for Troubleshooting MySQL Concurrency Issues May, 23, 2018 Sveta Smirnova Introduction This is very personal webinar No intended use No best practices No QA-specific tools Real life

More information

THREADS: (abstract CPUs)

THREADS: (abstract CPUs) CS 61 Scribe Notes (November 29, 2012) Mu, Nagler, Strominger TODAY: Threads, Synchronization - Pset 5! AT LONG LAST! Adversarial network pong handling dropped packets, server delays, overloads with connection

More information

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14

APT Session 4: C. Software Development Team Laurence Tratt. 1 / 14 APT Session 4: C Laurence Tratt Software Development Team 2017-11-10 1 / 14 http://soft-dev.org/ What to expect from this session 1 C. 2 / 14 http://soft-dev.org/ Prerequisites 1 Install either GCC or

More information

CSE au Midterm Exam Nov. 2, 2018 Sample Solution

CSE au Midterm Exam Nov. 2, 2018 Sample Solution Question 1. (16 points) Build tools and make. We re building a C++ software back-end prototype for a new food web site. So far, we ve got the following source files with the code for two main programs

More information

Lec 26: Parallel Processing. Announcements

Lec 26: Parallel Processing. Announcements Lec 26: Parallel Processing Kavita Bala CS 341, Fall 28 Computer Science Cornell University Announcements Pizza party Tuesday Dec 2, 6:3-9: Location: TBA Final project (parallel ray tracer) out next week

More information

Binghamton University. CS-211 Fall Variable Scope

Binghamton University. CS-211 Fall Variable Scope Variable Scope 1 Scope The places in your code that can read and/or write a variable. Scope starts at the location where you declare the variable There may be holes in the scope! Scope ends at the end

More information

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables Graded assignment 0 will be handed out in section Assignment 1 Not that bad Check your work (run it through the compiler) Factorial Program Prints out ENTERING, LEAVING, and other pointers unsigned char

More information

JENET C LIBRARY API ver. 3.00

JENET C LIBRARY API ver. 3.00 JENET C LIBRARY API ver. 3.00 Document Version: 2.0 Document Revision: November, 29 2007 FP, UZ, MV Helper function library for developing user applications to control a Jenet Ethernet Camac Crate Controller.

More information

CSE 374 Programming Concepts & Tools

CSE 374 Programming Concepts & Tools CSE 374 Programming Concepts & Tools Hal Perkins Fall 2017 Lecture 8 C: Miscellanea Control, Declarations, Preprocessor, printf/scanf 1 The story so far The low-level execution model of a process (one

More information

Threaded Programming. Lecture 9: Alternatives to OpenMP

Threaded Programming. Lecture 9: Alternatives to OpenMP Threaded Programming Lecture 9: Alternatives to OpenMP What s wrong with OpenMP? OpenMP is designed for programs where you want a fixed number of threads, and you always want the threads to be consuming

More information

OS lpr. www. nfsd gcc emacs ls 1/27/09. Process Management. CS 537 Lecture 3: Processes. Example OS in operation. Why Processes? Simplicity + Speed

OS lpr. www. nfsd gcc emacs ls 1/27/09. Process Management. CS 537 Lecture 3: Processes. Example OS in operation. Why Processes? Simplicity + Speed Process Management CS 537 Lecture 3: Processes Michael Swift This lecture begins a series of topics on processes, threads, and synchronization Today: processes and process management what are the OS units

More information

Binghamton University. CS-211 Fall Variable Scope

Binghamton University. CS-211 Fall Variable Scope Variable Scope 1 Scope The places in your code that can read and/or write a variable. Scope starts at the location where you declare the variable There may be holes in the scope! Scope ends at the end

More information

CPSC 341 OS & Networks. Threads. Dr. Yingwu Zhu

CPSC 341 OS & Networks. Threads. Dr. Yingwu Zhu CPSC 341 OS & Networks Threads Dr. Yingwu Zhu Processes Recall that a process includes many things An address space (defining all the code and data pages) OS resources (e.g., open files) and accounting

More information

Creating a Shell or Command Interperter Program CSCI411 Lab

Creating a Shell or Command Interperter Program CSCI411 Lab Creating a Shell or Command Interperter Program CSCI411 Lab Adapted from Linux Kernel Projects by Gary Nutt and Operating Systems by Tannenbaum Exercise Goal: You will learn how to write a LINUX shell

More information

RMT & CCE porting to *NIX

RMT & CCE porting to *NIX RMT & CCE porting to *NIX by A.Kazakov, July-August 2007 Current State The original RMT & CCE source code has been ported to epics OSI environment. And virtually would compile (and hopefully work) under

More information

4.8 Summary. Practice Exercises

4.8 Summary. Practice Exercises Practice Exercises 191 structures of the parent process. A new task is also created when the clone() system call is made. However, rather than copying all data structures, the new task points to the data

More information

POSIX Threads. HUJI Spring 2011

POSIX Threads. HUJI Spring 2011 POSIX Threads HUJI Spring 2011 Why Threads The primary motivation for using threads is to realize potential program performance gains and structuring. Overlapping CPU work with I/O. Priority/real-time

More information

Operating Systems and Networks Assignment 2

Operating Systems and Networks Assignment 2 Spring Term 2014 Operating Systems and Networks Assignment 2 Assigned on: 27th February 2014 Due by: 6th March 2014 1 Scheduling The following table describes tasks to be scheduled. The table contains

More information

Homework 2 Answers. Due Date: Monday, April 29, 2002, at 11:59PM Points: 100

Homework 2 Answers. Due Date: Monday, April 29, 2002, at 11:59PM Points: 100 Homework 2 Answers Due Date: Monday, April 29, 2002, at 11:59PM Points: 100 UNIX System 1. (10 points) What program is running as process #1? Type ps ax and look for the process with a PID of 1. Then look

More information

Reading compiler errors

Reading compiler errors Reading compiler errors ls2.c:1: error: expected =,,, ;, asm or attribute before : token In file included from /usr/include/stdio.h:75, from ls2.c:12: /usr/include/libio.h:332: error: expected specifier-qualifier-list

More information

Lab 4: Tracery Recursion in C with Linked Lists

Lab 4: Tracery Recursion in C with Linked Lists Lab 4: Tracery Recursion in C with Linked Lists For this lab we will be building on our previous lab at the end of the previous lab you should have had: #include #include char * make_string_from

More information

TCSS 422: OPERATING SYSTEMS

TCSS 422: OPERATING SYSTEMS TCSS 422: OPERATING SYSTEMS OBJECTIVES Introduction to threads Concurrency: An Introduction Wes J. Lloyd Institute of Technology University of Washington - Tacoma Race condition Critical section Thread

More information

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables) Memory Allocation Memory What is memory? Storage for variables, data, code etc. How is memory organized? Text (Code) Data (Constants) BSS (Global and static variables) Text Data BSS Heap Stack (Local variables)

More information

A brief introduction to C++

A brief introduction to C++ A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne

More information

Operating Systems, Assignment 2 Threads and Synchronization

Operating Systems, Assignment 2 Threads and Synchronization Operating Systems, Assignment 2 Threads and Synchronization Responsible TA's: Zohar and Matan Assignment overview The assignment consists of the following parts: 1) Kernel-level threads package 2) Synchronization

More information

1 Introduction. 2 total-store-order. Take me for a spin. 2.1 Peterson's algorithm. Johan Montelius HT2016

1 Introduction. 2 total-store-order. Take me for a spin. 2.1 Peterson's algorithm. Johan Montelius HT2016 Take me for a spin Johan Montelius HT2016 1 Introduction We will rst experience that we can not implement any synchronization primitives using regular read and write operations. Then we will implement

More information

CSE 333 Lecture 9 - storage

CSE 333 Lecture 9 - storage CSE 333 Lecture 9 - storage Steve Gribble Department of Computer Science & Engineering University of Washington Administrivia Colin s away this week - Aryan will be covering his office hours (check the

More information

Armide Documentation. Release Kyle Mayes

Armide Documentation. Release Kyle Mayes Armide Documentation Release 0.3.1 Kyle Mayes December 19, 2014 Contents 1 Introduction 1 1.1 Features.................................................. 1 1.2 License..................................................

More information

Thread Concept. Thread. No. 3. Multiple single-threaded Process. One single-threaded Process. Process vs. Thread. One multi-threaded Process

Thread Concept. Thread. No. 3. Multiple single-threaded Process. One single-threaded Process. Process vs. Thread. One multi-threaded Process EECS 3221 Operating System Fundamentals What is thread? Thread Concept No. 3 Thread Difference between a process and a thread Prof. Hui Jiang Dept of Electrical Engineering and Computer Science, York University

More information

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University

CS 333 Introduction to Operating Systems. Class 3 Threads & Concurrency. Jonathan Walpole Computer Science Portland State University CS 333 Introduction to Operating Systems Class 3 Threads & Concurrency Jonathan Walpole Computer Science Portland State University 1 The Process Concept 2 The Process Concept Process a program in execution

More information

POSIX PTHREADS PROGRAMMING

POSIX PTHREADS PROGRAMMING POSIX PTHREADS PROGRAMMING Download the exercise code at http://www-micrel.deis.unibo.it/~capotondi/pthreads.zip Alessandro Capotondi alessandro.capotondi(@)unibo.it Hardware Software Design of Embedded

More information

POSIX / System Programming

POSIX / System Programming POSIX / System Programming ECE 650 Methods and Tools for Software Eng. Guest lecture 2017 10 06 Carlos Moreno cmoreno@uwaterloo.ca E5-4111 2 Outline During today's lecture, we'll look at: Some of POSIX

More information

Maemo Diablo Source code for the LibOSSO RPC examples Training Material

Maemo Diablo Source code for the LibOSSO RPC examples Training Material Maemo Diablo Source code for the LibOSSO RPC examples Training Material February 9, 2009 Contents 1 Source code for the LibOSSO RPC examples 2 1.1 libosso-example-sync/libosso-rpc-sync.c..............

More information

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT C Review MaxMSP Developers Workshop Summer 2009 CNMAT C Syntax Program control (loops, branches): Function calls Math: +, -, *, /, ++, -- Variables, types, structures, assignment Pointers and memory (***

More information

Chapter 4 Concurrent Programming

Chapter 4 Concurrent Programming Chapter 4 Concurrent Programming 4.1. Introduction to Parallel Computing In the early days, most computers have only one processing element, known as the Central Processing Unit (CPU). Due to this hardware

More information

CSC209H Lecture 3. Dan Zingaro. January 21, 2015

CSC209H Lecture 3. Dan Zingaro. January 21, 2015 CSC209H Lecture 3 Dan Zingaro January 21, 2015 Streams (King 22.1) Stream: source of input or destination for output We access a stream through a file pointer (FILE *) Three streams are available without

More information

C++ Tutorial AM 225. Dan Fortunato

C++ Tutorial AM 225. Dan Fortunato C++ Tutorial AM 225 Dan Fortunato Anatomy of a C++ program A program begins execution in the main() function, which is called automatically when the program is run. Code from external libraries can be

More information

Case Study: Parallelizing a Recursive Problem with Intel Threading Building Blocks

Case Study: Parallelizing a Recursive Problem with Intel Threading Building Blocks 4/8/2012 2:44:00 PM Case Study: Parallelizing a Recursive Problem with Intel Threading Building Blocks Recently I have been working closely with DreamWorks Animation engineers to improve the performance

More information

Mysql Tutorial Show Table Like Name Not >>>CLICK HERE<<<

Mysql Tutorial Show Table Like Name Not >>>CLICK HERE<<< Mysql Tutorial Show Table Like Name Not SHOW TABLES LIKE '%shop%' And the command above is not working as Table name and next SHOW CREATE TABLEcommand user889349 Apr 18. If you do not want to see entire

More information

NVJPEG. DA _v0.2.0 October nvjpeg Libary Guide

NVJPEG. DA _v0.2.0 October nvjpeg Libary Guide NVJPEG DA-06762-001_v0.2.0 October 2018 Libary Guide TABLE OF CONTENTS Chapter 1. Introduction...1 Chapter 2. Using the Library... 3 2.1. Single Image Decoding... 3 2.3. Batched Image Decoding... 6 2.4.

More information

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14 C introduction Variables Variables 1 / 14 Contents Variables Data types Variable I/O Variables 2 / 14 Usage Declaration: t y p e i d e n t i f i e r ; Assignment: i d e n t i f i e r = v a l u e ; Definition

More information

CSE 333 SECTION 3. POSIX I/O Functions

CSE 333 SECTION 3. POSIX I/O Functions CSE 333 SECTION 3 POSIX I/O Functions Administrivia Questions (?) HW1 Due Tonight HW2 Due Thursday, July 19 th Midterm on Monday, July 23 th 10:50-11:50 in TBD (And regular exercises in between) POSIX

More information

Introduction to troubleshooting Basic techniques. Sveta Smirnova Principal Support Engineer March, 10, 2016

Introduction to troubleshooting Basic techniques. Sveta Smirnova Principal Support Engineer March, 10, 2016 Introduction to troubleshooting Basic techniques Sveta Smirnova Principal Support Engineer March, 10, 2016 Table of Contents Introduction How to find problematic query Solving issues Syntax errors Logic

More information

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems

Deep C. Multifile projects Getting it running Data types Typecasting Memory management Pointers. CS-343 Operating Systems Deep C Multifile projects Getting it running Data types Typecasting Memory management Pointers Fabián E. Bustamante, Fall 2004 Multifile Projects Give your project a structure Modularized design Reuse

More information

Data and File Structures Laboratory

Data and File Structures Laboratory Tools: Gcov, Cscope, Ctags, and Makefiles Assistant Professor Machine Intelligence Unit Indian Statistical Institute, Kolkata August, 2018 1 Gcov 2 Cscope 3 Ctags 4 Makefiles Gcov Gcov stands for GNU Coverage

More information