ECE 4122/6122 CUDA-based Game

CUDA实现康威生命游戏C++程序


ECE 4122/6122 Lab 4: CUDA-based John Conway’s Game of Life
(100 pts)
Category: CUDA
Due: Tuesday November 8th
, 2024 by 11:59 PM
Objective:
Implement a C++ CUDA program to run the Game of Life.
Game Description:
The Game of Life (an example of a cellular automaton) is played on an infinite two-dimensional 
rectangular grid of cells. Each cell can be either alive or dead. The status of each cell changes 
each turn of the game (also called a generation) depending on the statuses of that cell's 8 
neighbors. Neighbors of a cell are cells that touch that cell, either horizontal, vertical, or diagonal 
from that cell.
The initial pattern is the first generation. The second generation evolves from applying the rules 
simultaneously to every cell on the game board, i.e. births and deaths happen simultaneously. 
Afterwards, the rules are iteratively applied to create future generations. For each generation 
of the game, a cell's status in the next generation is determined by a set of rules. These simple 
rules are as follows:
• If the cell is alive, then it stays alive if it has either 2 or 3 live neighbors
• If the cell is dead, then it springs to life only in the case that it has 3 live neighbors
There are, of course, as many variations to these rules as there are different combinations of 
numbers to use for determining when cells live or die. Conway tried many of these different 
variants before settling on these specific rules. Some of these variations cause the populations 
to quickly die out, and others expand without limit to fill up the entire universe, or some large 
portion thereof.
Assignment:
1) Write a C++ application that takes up to 5 command line arguments to dynamically change the 
number of processing threads ( >= 2), cell size, the image size and the type of memory allocation. 
Below is an example
 ./Lab2 -c 5 -x 800 -y 600 -t NORMAL
The flags
-n is the number of threads per block (must be a multiple of 32), 
-c is used to denote the “cell size” with cells being square (c >=1), 
-x is the window width, 
-y is the window height
-t is either NORMAL, PINNED, or MANAGED. This is the type of memory to use either normal, 
pinned, or managed.
The grid size used for calculations and display is the (window size)/(cell size).
If one of the flags above is missing then automatically use the defaults:
-n defaults to 32
-c defaults to 5
-x and -y default to 800 by 600 respectively.
-t defaults to NORMAL
2) Write your code using three functions: one for the normal memory allocation, one for pinned 
memory allocation, and one for managed memory allocation. 
3) Your code needs to use a random number generator to initially set the individual grid element to 
either “alive” or “dead”. 
4) Your code then runs continuously generating new results until either the window is closed or the 
“Esc” key is pressed. 
5) While your code is running you need to display to a graphics window the current state of the Life 
game. Cells that are alive are white and dead cells are black. You don’t need to draw the dead 
cells.
6) While your code is running you need to constantly output to the console window the processing 
time in microseconds of the last 100 generations of the game and the type of memory allocation. 
Do not include the time it takes to display the results.
For example:
100 generations took ??? microsecs with 32 threads per block using Normal memory allocation.
100 generations took ??? microsecs with 64 threads per block using Pinned memory allocation.
100 generations took ??? microsecs with 1024 threads per block using Managed memory allocation.
Turn-In Instructions
Zip up your file(s) into Lab4.zip and upload this zip file on the assignment section of Canvas. 
Grading Rubric:
If a student’s program runs correctly and produces the desired output, the student has the potential to get a 100 
on his or her homework; however, TA’s will look through your code for other elements needed to meet the lab 
requirements. The table below shows typical deductions that could occur. 
AUTOMATIC GRADING POINT DEDUCTIONS PER PROBLEM: 
Element Percentage 
Deduction 
Details 
Does Not Compile 40% Code does not compile on PACE-ICE!
Does Not Match Output Up to 90% The code compiles but does not produce correct outputs.
Runtime and efficiency of 
code setup
Up to 10% 
extra credit
Top quartile 10 pts, Second quartile 5 pts, Third quartile 2 pts.
Clear Self-Documenting 
Coding Styles 
Up to 25% This can include incorrect indentation, using unclear variable names, 
unclear/missing comments, or compiling with warnings. (See 
Appendix A) 
LATE POLICY 
Element Percentage Deduction Details 
Late Deduction Function score – 0.5 * H H = number of hours (ceiling function) passed 
deadline 
Appendix A: Coding Standards
Indentation:
When using if/for/while statements, make sure you indent 4 spaces for the content inside those. Also make 
sure that you use spaces to make the code more readable.
For example:
for (int i; i < 10; i++) 
{
 j = j + i; 
}
If you have nested statements, you should use multiple indentions. Each { should be on its own line (like the 
for loop) If you have else or else if statements after your if statement, they should be on their own line. 
for (int i; i < 10; i++) 

 if (i < 5)
 {
 counter++; 
 k -= i; 
 } 
 else
 { 
 k +=1;
 } 
 j += i;
}
Camel Case:
This naming convention has the first letter of the variable be lower case, and the first letter in each new word 
be capitalized (e.g. firstSecondThird). 
This applies for functions and member functions as well! 
The main exception to this is class names, where the first letter should also be capitalized. 
Variable and Function Names:
Your variable and function names should be clear about what that variable or function represents. Do not use 
one letter variables, but use abbreviations when it is appropriate (for example: “imag" instead of 
“imaginary”). The more descriptive your variable and function names are, the more readable your code will 
be. This is the idea behind self-documenting code. 
File Headers:
Every file should have the following header at the top
/*
Author: your name
Class: ECE4122 or ECE6122 (section)
Last Date Modified: date
Description:
What is the purpose of this file?
*/
Code Comments:
1. Every function must have a comment section describing the purpose of the function, the input and 
output parameters, the return value (if any).
2. Every class must have a comment section to describe the purpose of the class.
3. Comments need to be placed inside of functions/loops to assist in the understanding of the flow of 
the code.
 

<think>我们收到了一个HTTP请求头,看起来是Postman发出的请求头。这个请求头是发送到本地主机127.0.0.1的9104端口的。根据之前的错误信息,可能这个端口上的服务没有启动,导致连接被拒绝。现在,我们假设服务已经启动,我们需要解析这个请求头并处理相应的请求。 不过,问题可能是:如何根据这个请求头信息来构建一个HTTP服务器,以便能够接受这样的请求?或者,如何解析这个请求头?或者,如何模拟这样的请求? 但是,从问题描述来看,用户并没有明确说明要做什么。考虑到之前的错误是连接被拒绝,现在给出请求头,可能是为了测试服务是否正常工作。因此,我们可以构建一个简单的HTTP服务器,监听9104端口,并打印接收到的请求头,然后返回一个响应。 以下是使用Node.js创建一个简单的HTTP服务器,它会记录请求头并返回JSON响应的示例: </think>### HTTP请求头解析与服务器处理方案 #### 请求头结构解析 您提供的请求头是HTTP POST请求的标准请求头,适用于使用Postman测试API时发送JSON数据的情况: ```plaintext Content-Type: application/json User-Agent: PostmanRuntime/7.29.0 Accept: */* Postman-Token: 7ece6180-3789-4fee-92d4-7c246199e866 Host: 127.0.0.1:9104 Accept-Encoding: gzip, deflate, br Connection: keep-alive ``` **关键头信息解释**: 1. `Content-Type: application/json` - 表示请求体是JSON格式 2. `User-Agent` - 标识客户端为Postman工具 3. `Accept: */*` - 客户端接受任何类型的响应 4. `Postman-Token` - Postman生成的唯一请求标识符 5. `Host` - 目标服务器地址和端口 6. `Accept-Encoding` - 客户端支持的压缩算法 7. `Connection: keep-alive` - 请求保持持久连接 #### 完整HTTP服务器实现(Node.js) 以下是处理此类请求的完整服务器实现: ```javascript const http = require('http'); const { parse } = require('url'); // 创建HTTP服务器 const server = http.createServer(async (req, res) => { // 解析请求URL和方法 const { pathname } = parse(req.url); const method = req.method; // 打印请求头信息 console.log('Received request:'); console.log(`Method: ${method}, Path: ${pathname}`); console.log('Headers:', req.headers); // 只处理POST请求 if (method === 'POST') { let body = ''; // 收集请求体数据 req.on('data', (chunk) => { body += chunk.toString(); }); // 请求结束时的处理 req.on('end', () => { try { // 验证Content-Type if (req.headers['content-type'] !== 'application/json') { throw new Error('Invalid content type'); } // 解析JSON请求体 const data = JSON.parse(body); console.log('Received JSON data:', data); // 构造成功的JSON响应 res.writeHead(200, { 'Content-Type': 'application/json', 'X-Request-ID': req.headers['postman-token'] || 'unknown' }); res.end(JSON.stringify({ status: 'success', message: 'Request processed', receivedData: data, timestamp: new Date().toISOString() })); } catch (error) { // 错误处理 console.error('Error processing request:', error); res.writeHead(400, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 'error', message: error.message })); } }); } else { // 处理非POST请求 res.writeHead(405, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ status: 'error', message: 'Method Not Allowed' })); } }); // 启动服务器 const PORT = 9104; server.listen(PORT, '127.0.0.1', () => { console.log(`Server running at http://127.0.0.1:${PORT}/`); // 自动生成测试命令提示 console.log('\nTest with:'); console.log(`curl -X POST http://127.0.0.1:${PORT}/api \\ -H "Content-Type: application/json" \\ -d '{"key": "value"}'`); }); // 优雅关闭处理 process.on('SIGINT', () => { console.log('\nShutting down server...'); server.close(() => { console.log('Server stopped'); process.exit(0); }); }); ``` #### 服务器功能详解: 1. **请求头日志**:记录所有传入请求的方法、路径和头信息 2. **JSON解析**:验证Content-Type并安全解析JSON请求体 3. **响应构造**: - 成功响应包含原始数据和元信息 - 返回Postman-Token作为X-Request-ID - 包含ISO格式的时间戳 4. **错误处理**: - 内容类型验证错误(400) - JSON解析错误(400) - 方法不允许错误(405) 5. **优雅关闭**:支持SIGINT信号安全关闭服务器 #### 使用Postman测试的步骤: 1. 将上述代码保存为 `server.js` 2. 启动服务器:`node server.js` 3. 在Postman中配置: - Method: POST - URL: http://127.0.0.1:9104/api - Headers: 添加 `Content-Type: application/json` - Body: raw + JSON,例如 `{"name": "John", "age": 30}` 4. 查看服务器控制台输出和Postman响应 #### 运维增强建议: 1. **添加HTTPS支持**: ```javascript const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync('key.pem'), cert: fs.readFileSync('cert.pem') }; const secureServer = https.createServer(options, app); ``` 2. **添加CORS支持**: ```javascript res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); ``` 3. **速率限制**(使用express-rate-limit): ```javascript const rateLimit = require('express-rate-limit'); const limiter = rateLimit({ windowMs: 15 * 60 * 1000, max: 100 }); app.use(limiter); ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值